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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM