try...catch
try...catch語句標記要嘗試的語句塊,並指定一個出現異常時拋出的響應。
語法
try {
// 需要被執行的語句。
// try_statements
}
// 如果在try塊里有異常被拋出時執行的語句。
catch (exception) {
// catch_statements
}
// 在try語句塊之后執行的語句塊。無論是否有異常拋出或捕獲這些語句都將執行。
finally {
// finally_statements
}
描述
try語句包含了由一個或者多個語句組成的try塊, 和至少一個catch塊或者一個finally塊的其中一個,或者兩個兼有, 下面是三種形式的try聲明:
- try...catch;
- try...catch...finally;
- try...finally;
catch子句包含try塊中拋出異常時要執行的語句。也就是,你想讓try語句中的內容成功, 如果沒成功,你想控制接下來發生的事情,這時你可以在catch語句中實現。 如果在try塊中有任何一個語句(或者從try塊中調用的函數)拋出異常,控制立即轉向catch子句。如果在try塊中沒有異常拋出,會跳過catch子句。
finally子句在try塊和catch塊之后執行但是在下一個try聲明之前執行。無論是否有異常拋出或捕獲它總是執行。
你可以嵌套一個或者更多的try語句。如果內部的try語句沒有catch子句,那么將會進入包裹它的try語句的catch子句。
條件catch塊
你也可以用一個或者更多條件catch子句來處理特定的異常。在這種情況下,當異常拋出時將會進入合適的catch子句中。在下面的代碼中,try塊的代碼可能會拋出三種異常:TypeError,RangeError和EvalError。當一個異常拋出時,控制將會進入與其對應的catch語句。如果這個異常不是特定的,那么控制將轉移到無條件catch子句。
當用一個無條件catch子句和一個或多個條件語句時,無條件catch子句必須放在最后。否則當到達條件語句之前所有的異常將會被非條件語句攔截。
不符合ECMAscript 規范的示例
try {
myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
// statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
// statements to handle EvalError exceptions
} catch (e) {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
符合ECMAscript 規范的示例
try {
myroutine();
} catch (e) {
// statements to handle this very common expected error
if (e instanceof TypeError) {
// statements to handle this very common expected error
} else {
throw e; // re-throw the error unchanged
}
}
嵌套 try 塊
示例 1
try {
try {
// throw 語句拋出一個錯誤 錯誤發生時JavaScript會停止並拋出錯誤信息
throw new Error('oops');
}
finally {
console.log('finally');
}
}
catch (e) {
console.error('outer', e.message);
}
// Output:
// 'finally'
// 'outer' 'oops'
示例 2
try {
try {
throw new Error('oops');
}
catch (e) {
console.error('inner', e.message);
throw e;
}
finally {
console.log('finally');
}
}
catch (e) {
console.error('outer', e.message);
}
// Output:
// 'inner' 'oops'
// 'finally'
// 'outer' 'oops'
// 任何給定的異常只會被離它最近的封閉 catch 塊捕獲一次。當然,在“inner”塊拋出的任何新異常 (因為 catch 塊里的代碼也可以拋出異常),將會被“outer”塊所捕獲。