1. Home
  2. Interview Questions
  3. JavaScript
  4. How do try, catch and finally work, and what happens if fina…

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: The try block runs first. If it throws, control jumps to catch, and finally always runs afterwards, even if try or catch returned or threw. A return inside finally overrides any earlier return or thrown error, which can silently swallow exceptions.

Detailed explanation

A try statement has three parts. You need at least one of catch or finally.

  • try holds the code that might throw. If no error occurs, catch is skipped.
  • catch (err) runs only when something inside try throws. The thrown value, usually an Error object, is bound to err. Since ES2019 you can leave out the binding: catch { ... }.
  • finally runs in every case: after a normal finish, after catch handles an error, after a return, break or continue inside try, and even when catch itself throws. People use it for cleanup, such as closing a file handle, releasing a lock or hiding a loading spinner.

The tricky part is how finally deals with completion values. When try or catch reaches a return, the engine first evaluates the return expression and stores it. Then it runs finally, and only after that does the function actually return. This has three consequences:

  1. If finally has no return or throw, the stored value or error goes ahead unchanged.
  2. If finally runs return, that value replaces the stored one. If an error was on its way out, the error is discarded completely.
  3. If finally throws, the new error replaces whatever was pending.

Because the return value is evaluated before finally runs, reassigning a primitive variable inside finally does not change what gets returned. Mutating an object that was returned by reference does show up, because the caller receives that same object.

Also remember that try...catch only catches errors thrown synchronously while the try block is running. The one exception is an await inside an async function, where a rejected promise is rethrown at that point.

Example

function basic() {
  try {
    return 'from try';
  } finally {
    console.log('finally runs');
  }
}
basic(); // logs 'finally runs', returns 'from try'

function override() {
  try {
    throw new Error('boom');
  } catch (e) {
    return 'from catch';
  } finally {
    return 'from finally';
  }
}
override(); // 'from finally'

function swallow() {
  try {
    throw new Error('this error is lost');
  } finally {
    return 'ok';
  }
}
swallow(); // 'ok' with no error, the exception vanished

function evaluatedEarly() {
  let x = 1;
  try {
    return x;
  } finally {
    x = 2;
  }
}
evaluatedEarly(); // 1, not 2

// Typical real use: cleanup
async function loadData() {
  showSpinner();
  try {
    const res = await fetch('/api/data');
    return await res.json();
  } catch (err) {
    console.error('Load failed', err);
    return null;
  } finally {
    hideSpinner(); // runs on success and on failure
  }
}

Common mistakes

  • Putting a return in finally. It hides real bugs because thrown errors vanish without any trace. Many linters flag this, for example ESLint's no-unsafe-finally rule.
  • Thinking finally is skipped when try returns. It always runs before control leaves the block.
  • Writing an empty catch {} that swallows errors. At minimum, log the error or rethrow it if you cannot actually handle it.
  • Wrapping a callback-based or non-awaited async call in try and expecting its errors to be caught there.

Follow-up questions

  • What happens if the catch block itself throws an error?
  • When would you rethrow an error from catch instead of handling it?
  • How would you check whether a caught value is an Error object or something else?

Interview tip: Show the swallowed-error example where finally returns 'ok'. It proves you understand completion values, not just the basic syntax.

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 easy JavaScript questions

All easy questions →

Related Questions

‹
Q6 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