寫程式遇到需要判斷的情況,我們習慣用 if...else。但有些錯誤無法事先預判,這時就需要例外處理機制。JavaScript 的 try...catch...finally 能接住任何型別的物件——透過 throw 拋出,再由 catch 捕獲。
function demo() {
try {
throw new Error('koringz');
} catch (e) {
console.log(e.message);
} finally {
console.log('err finally');
}
}
demo();
// koringz
// err finally
規則可以濃縮成三句話:
若 try 中沒有錯誤,catch 完全不執行,finally 照樣執行。
throw 不限定錯誤物件,任何型別都能拋:
function demo() {
var array = [234],
newdate = new Date(),
fun = function () {},
is = 12.22,
call;
try {
throw array + '\n'
+ newdate.toLocaleString() + '\n'
+ fun.prototype.constructor + '\n'
+ (typeof is == 'number') + '\n'
+ call;
} catch (e) {
console.log(e);
} finally {
console.log('err finally');
}
}
demo();
// 234
// 2015/10/12 下午10:07:03
// function (){}
// true
// undefined
// err finally
實務上不建議這樣做。拋字串或數字會讓 catch 端失去 stack 資訊,除錯變得困難。應該拋 Error 物件(或自訂的錯誤子類別),才能取得有意義的堆疊。
這是 finally 最容易被忽略的行為。
function demo() {
try {
throw new Error('koringz');
} finally {
console.log('err finally');
return console.log('new finally');
}
}
demo();
// err finally
// new finally
注意這裡根本沒有 catch,錯誤卻沒有往外冒——因為 finally 中的 return 把整個流程提前結束了。
把 return 換到 catch 中,效果類似:
function demo() {
try {
throw new Error('koringz');
} catch (e) {
console.log('err finally');
return console.log('new finally');
}
}
demo();
// err finally
// new finally
而如果 try 沒有拋錯:
function demo() {
try {
// 空的
} catch (e) {
console.log('err finally');
return console.log('new finally');
}
}
demo();
// 什麼都不輸出
catch 沒被觸發,裡面的程式碼自然不執行。
結論:不要在 finally 區塊中寫 return、break 或 throw。它會吞掉原本要往外傳的例外,也會覆蓋 try 或 catch 中的回傳值,是 bug 的溫床。
try {
try {
throw new Error('open');
} catch (e) {
console.info(e.message);
throw e; // 重新拋出
} finally {
console.log('finally');
}
} catch (e) {
console.log('op', e.message);
}
// open
// finally
// op open
執行順序值得細看:內層 try 拋錯 → 內層 catch 印出訊息並重新拋出 → 內層 finally 執行 → 外層 catch 接手並印出。
由此可得兩條規則:
ES2019 之後也支援 optional catch binding,也就是 try {} catch {} 不帶參數的寫法,在不需要錯誤物件時更簡潔。