1. Home
  2. Interview Questions
  3. JavaScript
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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 setTimeout within 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 await line, which is still inside your try.
  • A promise without await inside try, such as try { 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/catch and assuming errors in the callback are covered.
  • Forgetting await (or return) on a promise inside try, 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

All hard questions →

Related Questions

‹
Q7 of 10 · JavaScript
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA