CodeZettaInterview Hub

JavaScript · Error Handling · Fresh / Intern · Concept

How do `try`, `catch`, and `finally` work in JavaScript?

Short Interview Answer

`try` runs code that may throw; `catch` handles the error; `finally` runs for cleanup whether the try succeeded or failed.

Detailed Explanation

When an exception is thrown, the stack unwinds to the nearest catch. `finally` executes before control leaves the construct — even on return inside try/catch. If `finally` throws, it can mask the original error. `catch` bindings are block-scoped. Prefer catching only where you can recover or add context; otherwise let errors bubble to a boundary. Works with `await` inside async functions to catch promise rejections.

Example

try {
  risky();
  return 1;
} catch (err) {
  console.error(err);
  return 0;
} finally {
  cleanup();
}

Interview Tip

Mention that finally runs even on return.

Common Mistake

Catching everything at the bottom and swallowing errors.

Did you know this answer?