- A catch block is only executed if an exception is thrown in the try block.
- A finally block is executed always after a try(-catch) block, if an exception is thrown or not.
> As a side-effect, returning from finally clears a thrown error:
Exceptions aren't "cleared," they are "finally-d." Because that's how finally works[2]. The final block, if evaluated, always overrides the result of the previous blocks. A slightly more interesting example of try-catch weirdness is how catch blocks are one of the few constructs that create new scope (technically augment scope):
function F() {
try {
throw "error";
} catch (err) {
err = {
"hello": "world"
}
var hoisted = "foo"
console.log(err)
} finally {
return hoisted; // works, since this gets hoisted to the top of F
return err; // breaks, since err is spooky and only "scoped" in the catch block
}
}
[2] https://tc39.es/ecma262/multipage/ecmascript-language-statem...