CodeZettaInterview Hub

JavaScript · Error Handling · Junior · Debugging

Why doesn't a surrounding try/catch always catch errors from async code, and how do you fix that?

Short Interview Answer

try/catch only catches synchronous throws / awaited rejections in that block; floating promises and callback errors escape unless handled.

Detailed Explanation

Calling an async function without await/`.catch` schedules work that rejects later — outside the original try. Event handlers and `setTimeout` callbacks need their own handling. Patterns: always await or attach catch; use global `unhandledrejection` as a last-resort logger; in UI frameworks use error boundaries for render errors (note: they don't catch all async). Wrap async event handlers. Lint floating promises.

Example

try {
  asyncTask(); // not awaited — rejection escapes
} catch (e) {
  // may not run
}

try {
  await asyncTask();
} catch (e) {
  // handles rejection
}

Interview Tip

This is a very common mid-level gotcha — be precise.

Common Mistake

Assuming React error boundaries catch promise rejections in handlers.

Did you know this answer?