← Back to JavaScript, page 9

javascript-0170 · Medium mid

What do these try, catch, and finally puzzles print, and when does finally override a return or a thrown error?

A finally block always runs after try and catch, even after return, break, continue, or a thrown error. The return value is evaluated before finally runs, but a return, throw, break, or continue inside finally replaces the earlier result, which can swallow an error. In async functions finally runs after the awaited work, and in generators it runs when the iterator is closed early.

Full answer

Rules of try, catch, and finally:

  1. finally runs whatever happens: normal completion, return, throw, break, or continue in the try or catch.
  2. A return value is evaluated first and saved. Then finally runs. If finally does not return, the saved value is returned. So return x++ followed by changes to x in finally returns the old value of x. But changing an object that was returned changes the same object.
  3. If finally itself contains return, throw, break, or continue, it overrides the pending result. A return in finally discards a thrown error, which silently swallows the error, and it also overrides an earlier return. Lint rules (no-unsafe-finally) forbid this.
  4. An error thrown in finally replaces any pending error or return value.
  5. An error thrown in catch still lets finally run, and then propagates.
  6. catch without a binding (catch { ... }) is allowed when the error is not used.
  7. Nested try blocks: inner finally runs before the outer catch.
  8. In loops, continue or break in try still runs finally for that pass.
  9. In async functions: await inside try makes finally wait for it. A rejection that is caught by catch does not reach the caller. return promise without await inside a try does not catch its rejection in that function's catch, because the function leaves the try before the promise settles, while return await promise does catch it.
  10. In generators: when a consumer stops early with break or return(), the generator resumes at the paused yield as if a return happened, so its finally blocks run. That is how cleanup works for iterators.

Practical use: finally is for cleanup that must happen: closing files, releasing locks, hiding a loading spinner. Do not return from finally. If cleanup can throw, handle that error inside the cleanup so it does not replace the original one.

javascript
const attempt = (label, fn) => {
  try {
    console.log(label.padEnd(36), '->', fn());
  } catch (error) {
    console.log(label.padEnd(36), '->', 'threw', error.message);
  }
};
const order = [];

attempt('1. return value saved before finally', () => {
  let x = 1;
  try { return x++; } finally { x = 100; order.push('x is ' + x); }
});
attempt('1b. returned object is shared', () => {
  const o = { n: 1 };
  try { return o; } finally { o.n = 2; }
});
attempt('2. return in finally wins', () => {
  try { return 'from try'; } finally { return 'from finally'; }
});
attempt('3. return in finally swallows an error', () => {
  try { throw new Error('lost'); } finally { return 'swallowed'; }
});
attempt('4. throw in finally replaces return', () => {
  try { return 'value'; } finally { throw new Error('from finally'); }
});
attempt('5. error in catch, finally still runs', () => {
  try { throw new Error('first'); } catch (e) { throw new Error('from catch'); } finally { order.push('cleanup ran'); }
});
attempt('6. optional catch binding', () => {
  try { JSON.parse('{'); } catch { return 'ignored the error'; }
});
attempt('7. inner finally before outer catch', () => {
  const steps = [];
  try {
    try { throw new Error('boom'); } finally { steps.push('inner finally'); }
  } catch (e) { steps.push('outer catch ' + e.message); } finally { steps.push('outer finally'); }
  return steps.join(', ');
});
attempt('8. continue and break run finally', () => {
  const seen = [];
  for (let i = 0; i < 4; i++) {
    try {
      if (i === 1) continue;
      if (i === 3) break;
      seen.push('body ' + i);
    } finally { seen.push('finally ' + i); }
  }
  return seen.join(', ');
});
attempt('9. finally can override a break', () => {
  let count = 0;
  for (let i = 0; i < 3; i++) { try { break; } finally { count++; if (i < 2) continue; } }
  return count;
});
console.log(order);

function* resource() {
  try { yield 1; yield 2; yield 3; } finally { console.log('generator cleanup ran'); }
}
for (const value of resource()) { if (value === 2) break; }

async function plainReturn() { try { return Promise.reject(new Error('rejected')); } catch { return 'caught inside'; } }
async function awaitedReturn() { try { return await Promise.reject(new Error('rejected')); } catch { return 'caught inside'; } }
async function asyncFinally() {
  try { await new Promise((r) => setTimeout(r, 1)); return 'try finished'; } finally { console.log('async finally after the await'); }
}
(async () => {
  console.log('plain return:', await plainReturn().catch((e) => 'caller got ' + e.message));
  console.log('return await:', await awaitedReturn());
  console.log(await asyncFinally());
})();

Run with Node.js v24.22.1 as js-170.js; two runs gave identical output. Output: 1. return value saved before finally -> 1 1b. returned object is shared -> { n: 2 } 2. return in finally wins -> from finally 3. return in finally swallows an error -> swallowed 4. throw in finally replaces return -> threw from finally 5. error in catch, finally still runs -> threw from catch 6. optional catch binding -> ignored the error 7. inner finally before outer catch -> inner finally, outer catch boom, outer finally 8. continue and break run finally -> body 0, finally 0, finally 1, body 2, finally 2, finally 3 9. finally can override a break -> 3 [ 'x is 100', 'cleanup ran' ] generator cleanup ran plain return: caller got rejected return await: caught inside async finally after the await try finished

Key points

  • finally runs after try and catch in every case, including return, break, continue, and throw.
  • The return value is computed before finally; a return or throw inside finally replaces it and can swallow errors.
  • An error in catch or finally changes the outcome; inner finally runs before outer catch.
  • return await inside try catches rejections, plain return of a promise does not.
  • Generators run finally when closed early; use finally for cleanup, not for control flow.

Common mistakes

  • Returning from finally and silently swallowing errors.
  • Expecting changes to a returned primitive in finally to change the result.
  • Writing return promise inside try and expecting the catch to see its rejection.
  • Throwing from cleanup code in finally and hiding the original error.

Follow-ups

  • Why does a return in finally discard a thrown error?
  • How does return await differ from return inside a try block?
  • Which lint rule catches unsafe finally blocks?

Tips

  • State the rule: return is evaluated first, finally runs, and a jump in finally wins.
  • Show the async return await case, since it is a common production bug.
  • Say what finally is for: cleanup.