捕获异常

try catch finally throw

try{

  // code1

}catch(e){

  // code1有错误的话,会执行catch里面的代码code2,e是code1里面报的错,必须带这个参数

  // code2

  

}finally{

 // code1 有没有错,都会执行finally里面的代码code3

 // code3

}

 

throw new Error(str); // 报错,throw后面必须是 错误对象,一般写函数的时候可以用,一旦报错后面的代码将不再执行

 

try{
  aolert(1);  
}catch(e){
  console.dir(e);
console.dir(e.name);

console.log("catch");
 // ReferenceError: aolert is not defined
 // 错误对象一般包括,e.name和 e.message 

}finally{
  console.log("finally")
}

function fn(num){
 if(typeof num !=="number"){
   throw new Error("fn的参数必须是数字类型")
 }
 console.log("right")
}

fn("1"); // Uncaught Error: fn的参数必须是数字类型
fn(1);

 

posted @ 2017-02-03 16:22  花.花  阅读(127)  评论(0编辑  收藏  举报