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的引擎捕獲。

 

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