Timer Callbacks Escape try catch Blocks
Show that a throw inside setTimeout never reaches the surrounding try catch, and route it to an uncaughtException handler instead.
Code
// Install the safety net first — it is the only handler that can
// observe a throw from a timer callback
process.on('uncaughtException', (err) => {
console.log(`process handler caught: ${err.message}`);
});
function scheduleFlakyWork() {
// This throw happens long after the calling stack returned
setTimeout(() => {
throw new Error('boom inside timer');
}, 20);
}
try {
scheduleFlakyWork();
console.log('try block finished without catching anything');
} catch {
// Unreachable: timer callbacks escape try catch blocks because the
// stack that ran the try block is gone by the time they fire
console.log('catch reached');
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
try block finished without catching anything
process handler caught: boom inside timerWhy the try block stays silent
scheduleFlakyWork only schedules the throw — setTimeout(() => { throw new Error('boom inside timer'); }, 20) fires after the calling stack has returned, so the surrounding try is out of the picture and its catch is unreachable, as the code’s own comment states. The try block’s line console.log('try block finished without catching anything') is the proof that the schedule call itself completed normally.
Where the throw actually lands
try block finished without catching anything
process handler caught: boom inside timer
process.on('uncaughtException', …) is the only handler that can observe the timer’s throw; it logs process handler caught: boom inside timer from err.message. Nothing prints catch reached in a real run — that branch exists to document why it cannot be reached. The ordering in the file matters: the handler is registered first, scheduleFlakyWork() is called second, and the throw happens last, 20 ms later; a handler registered after the throw fires would miss it.
The line that arms the net
process.on('uncaughtException', (err) => {
console.log(`process handler caught: ${err.message}`);
});
The handler sits at the top of the file precisely because the stack that ran the try block is gone by the time the timer callback throws.
Interactive Tools for This Topic
FAQ
- Does the code guard against bad input?
- The snippet does not validate input. `Error` is thrown unconditionally at its throw site — nothing guards it.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `scheduleFlakyWork` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.