js中的异常处理

js中的异常处理语句有两个,一个是try……catch……,一个是throw。

try……catch用于语法错误,错误有name和message两个属性。throw用于逻辑错误。

对于逻辑错误,js是不会抛出异常的,也就是说,用try catch没有用。这种时候,需要自己创建error对象的实例,然后用throw抛出异常。

(1)try……catch……的普通使用

错误内容:charAt()小写了

1 try{
2  var str="0123";
3  console.log(str.charat(2));
4 }catch(exception){
5     console.log("name属性-->"+exception.name);//name属性-->TypeError
6     console.log("message属性-->"+exception.message);//message属性-->str.charat is not a function
7 }

 (2)try……catch……无法捕捉到逻辑错误

错误内容:除数不能为0

try {
    var num=1/0;
    console.log(num);//Infinity
}catch(exception){
    console.log(exception.message);
}

(3)用throw抛出异常,需要自己现实例化一个error

注意:throw要用new关键字初始化一个Error,E要大写。同时,这个Error是异常里面的message属性!

try{
    var num=1/0;
    if(num=Infinity){
        throw new Error("Error大写,用new初始化-->除数不能为0");
    }
}
catch(exception){
    console.log(exception.message);
}

猜你喜欢

转载自www.cnblogs.com/qingshanyici/p/10464569.html
今日推荐