Errors thrown inside setTimeout callbacks occur asynchronously, in a different tick of the event loop. A try...catch around setTimeout itself (as in D) cannot catch errors thrown later in the scheduled callback.
To catch errors from countSheep() when it’s called asynchronously, the try...catch must wrap the call inside the timeout callback:
setTimeout(function() {
try {
countSheep();
} catch (e) {
handleError(e);
}
}, 1000);
B uses finally incorrectly and references e out of scope.
C is not valid JavaScript syntax.
D’s catch can only handle synchronous errors thrown before setTimeout returns, not those thrown inside the callback.
Contribute your Thoughts:
Chosen Answer:
This is a voting comment (?). You can switch to a simple comment. It is better to Upvote an existing comment if you don't have anything to add.
Submit