3.17 錯誤補捉(Errors)
在 javascript/practice
資料夾下,建立 try_catch.html
來練習。
try:檢查某一段程式,是否有錯誤。
catch:如果有錯誤,就執行這裡的程式。
throw:可自訂錯誤。
finally:執行完 try 和 catch 的程式之後,最後執行 finally 的程式。
範例 1:try...catch...
下例的第 2 行並不會執行,因為第 1 行跟本沒有 my_func
這個函式:
my_func("Welcome");
alert("hello");
那改成以下呢?(請觀察 console 印出的訊息。)透過 try...catch 這樣包起來,如果 try 區塊裡的程式有錯,就會中斷 try 裡的程式,然後透過 catch 區塊補捉錯誤,就執行 catch 裡的程式:
try{
my_func("Welcome");
alert("hello");
}catch(error){
alert("執行 error 的程式");
console.log(error);
}
alert("繼續執行");
範例 2:throw
先測試以下程式:
function division(x, y){
try {
return x / y;
} catch(error) {
return error;
}
}
var result1 = division(5, 2);
console.log(result1); // 2.5
var result2 = division(5, 0);
console.log(result2); // Infinity
改成以下,透過 throw 可以自訂丟出的錯誤訊息,如果 y 等於 0,那就執行 catch 裡的程式(主要在 try 區塊裡,加上 if 的那段程式):
function division(x, y){
try {
if(y == 0){
throw "分母不能等於 0。";
}
return x / y;
} catch(error) {
return error;
}
}
var result1 = division(5, 2);
console.log(result1); // 2.5
var result2 = division(5, 0);
console.log(result2); // 分母不能等於 0。
範例 3:finally
透過 finally ,可以在 try 和 catch 都執行完程式的時候,會接續執行 finally 區塊裡的程式:
function division(x, y){
try {
if(y == 0){
throw "分母不能等於 0。";
}
return x / y;
} catch(error) {
return error;
} finally{
console.log("執行完畢");
}
}
var result1 = division(5, 2);
console.log(result1); // 2.5
var result2 = division(5, 0);
console.log(result2); // 分母不能等於 0。
Last updated