- Home
- Interview Questions
- JavaScript
- Why can't try/catch catch an error thrown inside a setTimeou…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: try/catch only covers code that runs synchronously while the try block is on the call stack. A setTimeout callback or a promise reaction runs later, on a fresh stack, after the try block has already finished. So you must handle those errors inside the callback, with .catch(), or by using await inside try.
Detailed explanation
JavaScript runs on a single thread with an event loop. When you call setTimeout(fn, 0), the engine only schedules fn. The try block then completes, its frame is popped off the stack, and the handler is gone. When fn eventually runs as a macrotask, no enclosing try is on the stack. The error becomes an uncaught exception. In the browser it reaches window.onerror. In Node.js it triggers process's uncaughtException event and, by default, crashes the process.
Promises behave in a similar way. A rejection is never thrown into your synchronous code. It is stored in the promise and delivered to handlers in a microtask. If no handler is attached by the time the engine checks, the runtime reports an unhandled rejection. Browsers fire an unhandledrejection event. Node.js 15 and later terminate the process by default.
There are a few subtle cases interviewers like to probe:
- Synchronous throw inside a Promise executor is caught automatically and turned into a rejection. A throw inside a
setTimeoutwithin that executor is not, because it happens later on a different stack. - await inside try does work. The async function suspends, and when the awaited promise rejects, the engine resumes the function by throwing at the
awaitline, which is still inside yourtry. - A promise without await inside
try, such astry { doAsync(); }, is not caught, because the function returns a pending promise immediately. - Event listener callbacks follow the same rule as timers. A throw inside them is uncaught unless the listener handles it itself.
Example
// 1. Not caught: the callback runs after try has finished
try {
setTimeout(() => { throw new Error('timer boom'); }, 0);
} catch (e) {
console.log('never reached');
}
// Fix: handle inside the callback
setTimeout(() => {
try {
riskyWork();
} catch (e) {
console.error('handled', e);
}
}, 0);
// 2. Not caught: promise not awaited
try {
fetchUser(); // returns a rejected promise later
} catch (e) { /* never runs */ }
// Fix A: attach .catch
fetchUser().catch(err => console.error(err));
// Fix B: await inside an async function
async function main() {
try {
await fetchUser();
} catch (err) {
console.error('caught', err);
}
}
// 3. Executor nuance
new Promise(() => { throw new Error('a'); })
.catch(e => console.log('caught a')); // works
new Promise(() => {
setTimeout(() => { throw new Error('b'); }, 0); // uncaught
});
// Fix: reject explicitly
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('b')), 0);
}).catch(e => console.log('caught b'));
// 4. Global safety nets (log and report, not a replacement for local handling)
window.addEventListener('error', e => report(e.error));
window.addEventListener('unhandledrejection', e => report(e.reason));
// Node.js
process.on('unhandledRejection', reason => { report(reason); });
process.on('uncaughtException', err => {
report(err);
process.exit(1); // app state may be corrupt, so restart cleanly
});Common mistakes
- Wrapping a callback-based API call in
try/catchand assuming errors in the callback are covered. - Forgetting
await(orreturn) on a promise insidetry, which leaves the rejection unhandled. Returning a promise from.then()without chaining.catch()causes the same problem. - Using
process.on('uncaughtException')to keep a Node.js server running as if nothing happened. After an uncaught exception the application may be in an inconsistent state. Log the error, exit, and let a process manager restart the app. - Throwing inside a nested callback in a Promise executor instead of calling
reject.
Follow-up questions
- How would you promisify a callback-style function so its errors can be caught with await?
- What is the difference between the error and unhandledrejection events in the browser?
- How do error-handling middleware and async route handlers interact in Express?
Interview tip: Explain it in terms of the call stack. The try frame is gone by the time the callback runs. Then show how await brings the error back into the try block.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More hard JavaScript questions
- How do HttpOnly, Secure and SameSite cookie flags protect against XSS and CSRF? · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · 1 ans
- Why is using await inside a loop often slow, and how do you run async tasks in parallel? · 1 ans
Related Questions
- How do try, catch and finally work, and what happens if finally contains a return? · JavaScript · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- What does an async function return, and how does await pause execution without blocking? · JavaScript · 1 ans
- What is the difference between localStorage, sessionStorage and cookies in the browser? · JavaScript · 1 ans
- How do HttpOnly, Secure and SameSite cookie flags protect against XSS and CSRF? · JavaScript · 1 ans
- Why can you call a function declaration before it is defined but not a function expression? · JavaScript · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · JavaScript · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)