【JS】try...catch
zh-rocco opened this issue · comments
注意
catch
内一定要加 console.error(error)
,不然 try
块里出现 BUG 时你会想哭的
示例代码:
try {
...
} catch (error) {
console.error(error)
}
谁加谁知道,加了都说好
类似的还有 Promise,Promise 里的函数是被 try...catch
包裹着的
return
in finally
override try
function example() {
try {
return true;
} finally {
return false;
}
}
example(); // false
According to ECMA-262 (5ed, December 2009), in pp. 96:
The production
TryStatement : try Block Finally
is evaluated as follows:Let B be the result of evaluating Block.
Let F be the result of evaluating Finally.
If F.type is normal, return B.
Return F.
And from pp. 36:
The Completion type is used to explain the behaviour of statements (
break
,continue
,return
andthrow
) that perform nonlocal transfers of control. Values of the Completion type are triples of the form (type, value, target), where type is one ofnormal
,break
,continue
,return
, orthrow
, value is any ECMAScript language value or empty, and target is any ECMAScript identifier or empty.
It's clear that return false would set completion type of finally as return, which cause try ... finally to do 4. Return F.