js中的错误处理

使用try catch finallu这种机制 与一般语言相同

var r1,r2,s = null;
try{
r1 = s.length;
r2 = 100;
}catch(e){
    console.log("出错了");
}
finally{
    console.log("出错");
}

js有一个标准的error对象表示错误,还有从error派生出来的typeError reference error等错误对象。。我们在处理错误时,可以通过catch(e)捕获的变量e访问错误对象:

var r1,r2,s = null;
try{
r1 = s.length;
r2 = 100;
}catch(e){
    if(e instanceof TypeError)
    console.log("typeError");
}
finally{
   
}

也可以抛出错误,在catch中捕获这个错误

try{
    s = prompt("请输入一个数字");
    n = parseInt(s);
    if(isNaN(n)){
        throw new Error("输入错误");
    }
}catch(e){
    console.log("出错了")
}

错误传播:错误会一直向上层传播。直到被js的引擎捕获。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章