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