Full answer
Rules of try, catch, and finally:
finallyruns whatever happens: normal completion,return,throw,break, orcontinuein thetryorcatch.- A
returnvalue is evaluated first and saved. Thenfinallyruns. Iffinallydoes not return, the saved value is returned. Soreturn x++followed by changes toxinfinallyreturns the old value ofx. But changing an object that was returned changes the same object. - If
finallyitself containsreturn,throw,break, orcontinue, it overrides the pending result. Areturninfinallydiscards a thrown error, which silently swallows the error, and it also overrides an earlierreturn. Lint rules (no-unsafe-finally) forbid this. - An error thrown in
finallyreplaces any pending error or return value. - An error thrown in
catchstill letsfinallyrun, and then propagates. catchwithout a binding (catch { ... }) is allowed when the error is not used.- Nested try blocks: inner
finallyruns before the outercatch. - In loops,
continueorbreakintrystill runsfinallyfor that pass. - In
asyncfunctions:awaitinsidetrymakesfinallywait for it. A rejection that is caught bycatchdoes not reach the caller.return promisewithoutawaitinside atrydoes not catch its rejection in that function'scatch, because the function leaves thetrybefore the promise settles, whilereturn await promisedoes catch it. - In generators: when a consumer stops early with
breakorreturn(), the generator resumes at the pausedyieldas if a return happened, so itsfinallyblocks 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.
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.