Sub topic 4
Cleaning Up with finally
Some code has to run whether or not an operation succeeds. If you start a timer, you need to stop it. If you open a connection, you need to close it. If you set a "loading" flag, you need to clear it. The finally block holds that code. This chapter covers when finally runs, how it interacts with return and throw, and the mistakes that cause it to hide errors or change return values.
This chapter assumes you know how try and catch work from the previous chapter. It also assumes you understand how return exits a function, and how break and continue work in loops.
The Shape of a finally Block
A finally block goes after a try block, or after a try...catch pair. There are two valid forms:
// Form 1: try...finally (no catch)
try {
console.log('doing work');
} finally {
console.log('cleaning up');
}
// Form 2: try...catch...finally
try {
throw new Error('something broke');
} catch (err) {
console.log('handled:', err.message);
} finally {
console.log('cleaning up');
}try cannot appear alone. It needs a catch, a finally, or both.
The two forms have different purposes. try...catch...finally handles the error and then cleans up. try...finally cleans up and lets the error keep going to the caller. That second form is useful in low-level helper functions, which often cannot recover from a failure but still have to release whatever they acquired.
When finally Runs
finally runs every time control leaves the try block (or the catch block), however it leaves. The table lists each case.
| How `try` ends | Does `finally` run? | What happens after `finally` |
|---|---|---|
| Reaches the end normally | Yes | Execution continues after the statement |
| `return value` | Yes | The function returns `value` |
| An error is thrown, and a `catch` exists | Yes, after `catch` | Continues after the statement, unless `catch` threw |
| An error is thrown, and there is no `catch` | Yes | The error propagates to the caller |
| `break` or `continue` in a loop | Yes | The loop breaks or continues |
| `catch` itself throws | Yes | The new error propagates |
The diagram shows the same paths.
When try or catch ends, the engine records a pending completion: "finished normally", "return this value", or "throw this error". It then runs finally. If finally finishes normally, the engine carries out the pending completion. This model accounts for all of the behavior below.
Example: a timer that always stops
function withTimer(label, fn) {
console.time(label);
try {
return fn();
} finally {
console.timeEnd(label);
}
}
withTimer('work', () => 42); // logs the elapsed time, returns 42There is no catch. If fn throws, console.timeEnd still runs and the error still reaches whoever called withTimer. The helper does its cleanup and leaves the decision about the error to its caller.
Example: finally with continue
for (let i = 0; i < 3; i++) {
try {
if (i === 1) continue;
console.log('body', i);
} finally {
console.log('finally', i);
}
}
// body 0
// finally 0
// finally 1
// body 2
// finally 2On the second pass, continue skips the rest of the body, but finally still runs before the next iteration starts.
Example: catch throws, finally still runs
function risky() {
try {
throw new Error('first');
} catch (err) {
throw new Error('second');
} finally {
console.log('cleanup');
}
}
try {
risky();
} catch (err) {
console.log(err.message);
}
// cleanup
// secondThe error thrown in catch becomes the pending completion. finally runs, and then that error propagates.
The Main Pattern: Acquire, Try, Release
Most finally blocks follow this pattern: acquire a resource, use it inside try, release it in finally. The example below uses a fake connection object, so you can run it anywhere.
function openConnection(name) {
console.log(`open ${name}`);
return {
query(sql) {
if (sql.includes('DROP')) throw new Error(`Refused: ${sql}`);
return [`row for ${sql}`];
},
close() {
console.log(`close ${name}`);
},
};
}
function runQuery(sql) {
const conn = openConnection('db');
try {
return conn.query(sql);
} finally {
conn.close();
}
}
console.log(runQuery('SELECT 1')); // open db, close db, [ 'row for SELECT 1' ]
try {
runQuery('DROP TABLE users'); // open db, close db
} catch (err) {
console.log(err.message); // Refused: DROP TABLE users
}The acquisition happens before try, and this placement matters. If openConnection throws, nothing was opened, so there is nothing to close and finally should not run. Once acquisition succeeds, the resource is guaranteed to be released.
Common error: acquiring inside try
A common mistake is to declare the variable outside try and assign it inside:
function brokenRunQuery(sql) {
let conn;
try {
conn = openConnectionThatFails();
return conn.query(sql);
} finally {
conn.close(); // TypeError: Cannot read properties of undefined
}
}
function openConnectionThatFails() {
throw new Error('network down');
}
try {
brokenRunQuery('SELECT 1');
} catch (err) {
console.log(err.message); // the TypeError message, not 'network down'
}If the connection fails to open, conn is undefined and conn.close() throws a TypeError. That new error replaces the real one, "network down", which is lost. Fix it by acquiring before try, or by guarding the cleanup with conn?.close() when acquisition has to stay inside try.
Gotchas That Change Results
A return in finally overrides everything
finally can replace the pending completion. A return inside finally discards whatever try or catch was about to do:
function pick() {
try {
return 'from try';
} finally {
return 'from finally';
}
}
console.log(pick()); // 'from finally'The same thing happens with a pending error. The error is thrown away with no trace:
function swallow() {
try {
throw new Error('this disappears');
} finally {
return 'everything is fine';
}
}
console.log(swallow()); // 'everything is fine'break and continue inside finally discard pending errors in the same way. Many linters flag this pattern; ESLint's no-unsafe-finally rule is one example. Keep return, break, continue, and throw out of finally.
A throw in finally masks the original error
Cleanup code can fail too. If it throws, the new error replaces the pending one:
function cleanupFails() {
try {
throw new Error('real problem');
} finally {
throw new Error('cleanup failed');
}
}
try {
cleanupFails();
} catch (err) {
console.log(err.message); // 'cleanup failed'
}The error you most need for debugging is gone. If the cleanup itself can fail, give it its own try...catch so it cannot override the main error:
function safeCleanup() {
try {
throw new Error('real problem');
} finally {
try {
throw new Error('cleanup failed');
} catch (cleanupErr) {
console.error('Cleanup error:', cleanupErr.message);
}
}
}
try {
safeCleanup();
} catch (err) {
console.log(err.message); // 'real problem'
}The return value is fixed before finally runs
When try executes return expr, the engine evaluates expr right away and stores the result. Reassigning the variable in finally does not change the stored value:
function snapshot() {
let count = 1;
try {
return count;
} finally {
count = 2;
}
}
console.log(snapshot()); // 1The stored value is still a reference, though. If it points to an object, mutations made in finally show up in the result:
function mutate() {
const state = { count: 1 };
try {
return state;
} finally {
state.count = 2;
}
}
console.log(mutate().count); // 2What finally Does Not Do
finally does not handle errors. A try...finally without catch lets every error through, and that is usually what you want from a helper.
finally also cannot run if the program never leaves the try block. An infinite loop never leaves it. Calling process.exit() in Node.js stops the process immediately, so a pending finally never runs:
// Node.js only
try {
process.exit(0);
} finally {
console.log('never printed');
}The same applies if the browser tab is closed or the process is killed. Do not rely on finally to survive a crash or a forced shutdown.
A Note on Asynchronous Code
finally follows the same rules inside an async function. A rejected await sends control to finally just as a synchronous throw does:
async function demo() {
try {
await Promise.reject(new Error('async failure'));
} finally {
console.log('cleanup after await');
}
}
demo().catch((err) => console.log(err.message));
// cleanup after await
// async failurePromises also have a .finally() method for chains. Later chapters cover asynchronous error handling in detail, including why a plain try cannot see errors from callbacks that run later.
Exercise
What does test() log and return? function test() { try { console.log('a'); return 'try'; } catch { return 'catch'; } finally { console.log('b'); } }
Show answer
It logs "a" and then "b", and returns 'try'. The try block never throws, so catch is skipped. The return value 'try' is stored as the pending completion, finally runs and logs "b", and then the function returns the stored value.
Exercise
A function opens a file handle inside try with handle = openFile(path) and calls handle.close() in finally. When openFile throws "file not found", the caller sees "Cannot read properties of undefined (reading 'close')". Explain why, and give two fixes.
Show answer
openFile threw before handle was assigned, so handle is undefined. Calling handle.close() in finally throws a TypeError, and that error replaces the original "file not found" error. Fix 1: call openFile before the try block, so finally only runs after a handle exists. Fix 2: guard the cleanup with handle?.close() so it does nothing when acquisition failed.
Exercise
Why does function f() { try { throw new Error('x'); } finally { return 0; } } return 0 without throwing, and how should you rewrite it if the goal is cleanup?
Show answer
The throw sets a pending error completion, but the return in finally replaces it, so the error is discarded. Remove the return from finally and put only the cleanup statements there. The error then propagates after cleanup, and the caller can handle it.