Sub topic 10
Why try/catch Misses Errors in Later Callbacks
This chapter assumes you know how try and catch work for synchronous code, and that you have used callback functions with setTimeout or event listeners. It explains a common surprise: a try block wrapped around code that schedules work does not protect the work itself.
The surprise
Run this script in Node.js or the browser console:
try {
setTimeout(() => {
throw new Error('boom');
}, 0);
} catch (err) {
console.log('This never runs');
}
console.log('try/catch finished');The output is try/catch finished, followed by an uncaught Error: boom. In Node.js the process crashes. The catch block never runs, even though the throw sits inside the try braces in the source code.
The working model: try/catch guards the call stack, not the source text
A try block protects the code that runs while that block is executing. It covers the functions it calls directly, the functions those call, and so on down the call stack. As soon as the block finishes, the protection is gone.
setTimeout does not run your callback. It registers the callback with the runtime and returns right away. The try block then ends without anything having gone wrong. Later, once the current script has finished, the event loop takes the callback from the task queue and calls it on a new, empty call stack. No try block is active on that stack, so the error has nowhere to go. The runtime reports it as uncaught.
The same rule applies to every API that calls your function later. That includes setInterval, DOM event listeners, Node.js EventEmitter handlers, and old-style Node callbacks such as fs.readFile(path, cb).
The fix: catch where the code actually runs
Put the try block inside the callback, so that it is on the stack when the error is thrown:
setTimeout(() => {
try {
throw new Error('boom');
} catch (err) {
console.log('Caught inside the callback:', err.message);
}
}, 0);Node-style callback APIs take a different approach. They don't throw. They pass the error to the callback as its first argument, and you check for it:
const fs = require('fs');
fs.readFile('missing.txt', 'utf8', (err, data) => {
if (err) {
console.error('Read failed:', err.code); // ENOENT
return;
}
console.log(data);
});Wrapping fs.readFile in an outer try would not catch this error. It would not even see it, because the error is delivered as a value and never thrown.
Common mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| Wrapping `setTimeout` or `addEventListener` in `try` | Only the registration is guarded | Put `try` inside the callback |
| Ignoring the `err` argument in a Node callback | The error is passed as a value, not thrown | Check `if (err)` first |
| Throwing inside a callback to "report" a failure | Nothing on that stack can catch it | Pass the error onward, or use promises |
Exercise
A button handler is registered inside a try block: try { button.addEventListener('click', () => JSON.parse('{bad')); } catch (e) { console.log('caught'); }. What happens when the user clicks the button, and how do you make the error get caught?
Show answer
The SyntaxError from JSON.parse is uncaught and "caught" is never logged. The try block only guarded the addEventListener call, which finished long before the click. Move the try/catch inside the arrow function so that it surrounds JSON.parse when the handler runs.
Exercise
Why does try { fs.readFile('x.txt', cb); } catch (e) {} fail to catch a missing-file error, even apart from timing?
Show answer
fs.readFile never throws a missing-file error. It passes the error as the first argument to cb. The callback has to check that argument itself.