Sub topic 4
Cleaning Up with finally
This chapter assumes you know how try and catch work, can write functions, and can run scripts in Node.js or the browser console. It covers the third clause of a try statement: finally.
What finally guarantees
A finally block runs after the try block (and the catch block, if there is one) no matter how they ended. That covers four cases:
trycompleted normally.trythrew an error andcatchhandled it.tryorcatchthrew an error that keeps propagating.tryorcatchran areturn,break, orcontinue.
So finally is the right place for cleanup that must always happen: closing a file, releasing a lock, stopping a timer, or hiding a loading spinner.
try...finally without catch
You don't need a catch to use finally. A try...finally pair lets an error pass through to the caller while still cleaning up on the way out:
function withTimer(label, fn) {
console.time(label);
try {
return fn();
} finally {
console.timeEnd(label);
}
}
withTimer('work', () => 42); // logs the elapsed time, returns 42If fn throws, console.timeEnd still runs and the error reaches the caller unchanged. Use this pattern when the current function has no useful way to recover but still owns a resource.
Order of execution with return
If try contains a return, the return value is computed first, then finally runs, and only then does the function actually return:
function demo() {
try {
console.log('try');
return 'value';
} finally {
console.log('finally');
}
}
console.log(demo());
// try
// finally
// valueThe same applies to cleanup around a resource:
function openConnection() {
return {
query(sql) {
if (sql === '') throw new Error('Empty query');
return `rows for ${sql}`;
},
close() {
console.log('connection closed');
},
};
}
function runQuery(sql) {
const conn = openConnection();
try {
return conn.query(sql);
} finally {
conn.close();
}
}
console.log(runQuery('SELECT 1')); // connection closed, then "rows for SELECT 1"
try {
runQuery('');
} catch (err) {
console.log('Caller saw:', err.message); // connection closed, then "Caller saw: Empty query"
}Notice that openConnection() is called before try. If opening fails, there is nothing to close, so the cleanup should not run.
The common mistake: control flow inside finally
A return inside finally replaces whatever try or catch was about to do, including a thrown error:
function pick() {
try {
return 'from try';
} finally {
return 'from finally';
}
}
console.log(pick()); // 'from finally'It is worse when try throws:
function swallow() {
try {
throw new Error('real problem');
} finally {
return 'everything is fine';
}
}
console.log(swallow()); // 'everything is fine' and the error is goneA throw inside finally does the same: the new error replaces the original. break and continue inside finally in a loop also discard a pending error.
Summary
| Situation in try/catch | Does finally run? | What happens after finally |
|---|---|---|
| Completes normally | Yes | Execution continues |
| Returns a value | Yes | The value is returned |
| Throws, caught by catch | Yes | Execution continues after the statement |
| Throws, not caught | Yes | The error propagates |
| finally itself returns | Yes | Its return value wins and any error is discarded |
Exercise
What does this code log, and why? function test() { let x = 1; try { return x; } finally { x = 2; console.log('x is', x); } } console.log(test());
Show answer
It logs "x is 2" and then 1. The return expression x is evaluated (giving 1) before finally runs. Changing x inside finally doesn't affect the value already scheduled to be returned, because finally has no return of its own.
Exercise
Rewrite this so the lock is always released, even if work() throws, without catching the error: lock.acquire(); work(); lock.release();
Show answer
Call lock.acquire() before the try, then write try { work(); } finally { lock.release(); }. Acquiring the lock outside the try means release only runs if acquire succeeded, and since there is no catch, any error from work() still reaches the caller.