try...catch 語句是什么?
try...catch 可以測試代碼中的錯誤。try 部分包含需要運行的代碼,而 catch 部分包含錯誤發生時運行的代碼。
try...catch語法:
try {
//在此運行代碼
}
catch(err){
//在此處理錯誤
}
運行流程:
try{...}包含塊中的代碼有錯誤,則運行catch(err){...}內的代碼,
否則不運行catch(err){...}內的代碼。
try...catch案例:
var array = null;
try {
document.write(array[0]);
} catch(err) {
document.writeln("Error name: " + err.name + "");
document.writeln("Error message: " + err.message);
}
try...catch...finally 語句
提供了一種方法來處理可能發生在給定代碼塊中的某些或全部錯誤,同時仍保持代碼的運行。如果發生了程序員沒有處理的錯誤,JS只給用戶提供它的普通錯誤信息,就好象沒有錯誤處理一樣。
finally :無論結果如何,都會執行這里面的語句
try...catch...finally 語法:
try {
tryStatements
}
catch(exception){
catchStatements
}
finally {
finallyStatements
}
參數
tryStatement
必選項。可能發生錯誤的語句。
exception
必選項。任何變量名。exception 的初始化值是扔出的錯誤的值。
catchStatement
可選項。處理在相關聯的 tryStatement 中發生的錯誤的語句。
finallyStatements
可選項。在所有其他過程發生之后無條件執行的語句
try...catch...finally 案例
var array = null;
try {
document.write(array[0]);
} catch(err) {
document.writeln("Error name: " + err.name + "");
document.writeln("Error message: " + err.message);
}
finally{
alert("object is null");
}
程序執行過程
1. array[0]的時候由於沒有創建array數組,array是個空對象,程序中調用array[0]就會產生object is null的異常
2. catch(err)語句捕獲到這個異常通過err.name打印了錯誤類型,err.message打印了錯誤的詳細信息.
3. finally類似於java的finally,無論有無異常都會執行.
