try {
setTimeout(() => {
throw new Error("late");
}, 0);
} catch (e) {
console.log("caught", e.message);
}
console.log("done");
Logs
done, then the error is uncaughtThe answer is "Logs done, then the error is uncaught". try/catch only covers code that runs synchronously inside it. setTimeout just schedules the callback. Then the try block finishes and done logs.
Later, the callback throws. By then there is no try on the call stack, so the error is uncaught. In Node, this crashes the process. To catch it, put the try inside the callback.
The tempting option "Logs done, then caught late" is wrong because the catch block has already finished when the callback runs.
Read more