Sub topic 1
Why Manual Cleanup Breaks: The try/finally Problem
Programs hold resources that must be given back: file handles, database connections, locks, timers, and temporary directories. JavaScript's garbage collector frees memory. It does not close a socket or release a lock at a predictable time. That job falls to you, and the usual tool for it is try/finally.
This chapter shows where try/finally works, where it fails, and why those failures are easy to write and hard to see in review. Later chapters introduce using and await using as the fix. Here the aim is to understand the problem well enough that the design of the fix makes sense.
Prerequisites
This chapter assumes you are comfortable with:
- Block scoping with
letandconst try/catch/finallysemantics, including whenfinallyruns- Promises and
async/await - ES classes and object literal methods
All examples run in Node.js 18 or later, or in a browser console. They use simulated resources, so they touch no real files or networks.
What Counts as a Resource
In this tutorial, a resource is any object that holds something outside the JavaScript heap and has to be released explicitly. Releasing it is called disposal or cleanup. Common examples:
| Resource | Acquire | Release | Cost of a leak |
|---|---|---|---|
| File handle | `fs.openSync` | `fs.closeSync` | File descriptor exhaustion (`EMFILE`) |
| DB connection | `pool.connect()` | `client.release()` | Pool starvation, requests hang |
| Lock or mutex | `lock.acquire()` | `lock.release()` | Deadlock |
| Interval timer | `setInterval` | `clearInterval` | Process never exits, repeated work |
| Event listener | `addEventListener` | `removeEventListener` | Memory growth, duplicate handlers |
Every row has the same shape. You acquire the resource, use it, and must release it on every path out of the code, including the paths where something throws.
The Leak You Get Without finally
Start with a simulated file API that records open handles, so a leak can be seen:
const openHandles = new Set();
function openFile(name) {
openHandles.add(name);
return {
name,
read() {
if (name.includes("corrupt")) throw new Error(`cannot read ${name}`);
return `header\nbody of ${name}`;
},
close() {
openHandles.delete(name);
},
};
}
function firstLine(name) {
const file = openFile(name);
const text = file.read(); // may throw
file.close(); // skipped if read() throws
return text.split("\n")[0];
}
console.log(firstLine("ok.txt")); // "header"
try {
firstLine("corrupt.txt");
} catch (e) {
console.log(e.message); // "cannot read corrupt.txt"
}
console.log([...openHandles]); // [ 'corrupt.txt' ] <- leakedThe happy path works and the tests pass. The leak shows up only when read() throws. That is the usual way these bugs reach production: they live on the error path, which gets the least testing.
The Standard Fix and Its Cost
try/finally guarantees cleanup on every exit: normal completion, return, break, continue, and throw.
function firstLineSafe(name) {
const file = openFile(name);
try {
const text = file.read();
return text.split("\n")[0];
} finally {
file.close();
}
}This is correct. It also has drawbacks that get worse as code grows:
- The acquisition and the release are far apart. A reader has to scroll to check that they match.
filemust be declared outside thetryso thefinallycan see it. Its scope is therefore wider than the code that actually uses it.- Nothing enforces the pattern. Forgetting it gives a silent leak, not an error.
With one resource these costs are small. The trouble begins with two.
Multiple Resources: Nesting or Bugs
Suppose you copy from one file to another. The correct version nests one try per resource:
function copy(src, dest) {
const input = openFile(src);
try {
const output = openFile(dest);
try {
return `copied ${input.read().length} chars to ${output.name}`;
} finally {
output.close();
}
} finally {
input.close();
}
}
console.log(copy("a.txt", "b.txt"));
console.log([...openHandles]); // only leftovers from earlier examplesEach new resource adds a level of indentation. With three or four resources, the code that does the work ends up deep inside the cleanup scaffolding.
Developers often flatten this to avoid the nesting. The flat version looks reasonable and has two bugs:
function copyFlat(src, dest) {
const input = openFile(src);
const output = openFile(dest); // bug 1: if this throws, input leaks
try {
return `copied ${input.read().length} chars`;
} finally {
input.close(); // bug 2: if this throws,
output.close(); // output is never closed
}
}Bug 1 is a partial acquisition leak. The second acquisition runs before any try protects the first one. Bug 2 is a cleanup chain break. One failing close() skips every cleanup after it. Fixing both by hand brings back the nesting, or needs a try/catch around each close() call.
Cleanup order matters as well. Resources usually depend on the ones acquired before them: a transaction depends on its connection, and a writer depends on its file. They should be released in reverse order of acquisition. Nested finally blocks get this right automatically. Flat code depends on the author remembering it.
When finally Throws, the Original Error Disappears
A finally block that throws replaces whatever exception was already propagating. The first error is lost:
function run() {
try {
throw new Error("body failed");
} finally {
throw new Error("cleanup failed");
}
}
try {
run();
} catch (e) {
console.log(e.message); // "cleanup failed" ("body failed" is gone)
}In practice the body error is usually the one you need. It describes the real fault, and the cleanup failure is often a side effect of it, such as a connection already broken by the failed query. Keeping both errors by hand looks like this:
function runPreservingErrors(resource) {
let bodyError;
let threw = false;
try {
throw new Error("body failed");
} catch (e) {
threw = true;
bodyError = e;
throw e;
} finally {
try {
resource.close();
} catch (cleanupError) {
if (threw) {
throw new AggregateError([bodyError, cleanupError], "body and cleanup failed");
}
throw cleanupError;
}
}
}
try {
runPreservingErrors({ close() { throw new Error("cleanup failed"); } });
} catch (e) {
console.log(e.errors.map((x) => x.message)); // [ 'body failed', 'cleanup failed' ]
}Almost nobody writes this, and the ones who do write it slightly differently each time. A later chapter shows how SuppressedError standardizes this exact situation.
Async Cleanup Adds a New Way to Fail
Async resources need their cleanup awaited. If you forget the await in finally, the function returns before the cleanup finishes, and any rejection from the cleanup becomes an unhandled rejection:
function makeConnection() {
let open = true;
return {
async query() {
if (!open) throw new Error("closed");
return [1];
},
async close() {
await new Promise((r) => setTimeout(r, 50));
open = false;
console.log("connection closed");
},
};
}
async function report() {
const conn = makeConnection();
try {
return await conn.query();
} finally {
conn.close(); // missing await: report() resolves before close completes
}
}
report().then((rows) => console.log("report done", rows));
// report done [ 1 ]
// connection closed <- logged afterwardsThe output order shows the problem. Code that runs after report() assumes the connection is closed when it is not. Tests that check for open handles become flaky. The fix is a single word, but nothing forces you to write it.
Ownership Transfer Is Awkward
Sometimes a function acquires resources, configures them, and returns them to the caller. Cleanup should happen only if setup fails partway. On success the caller becomes responsible. A finally block cannot express "clean up only on failure", so you switch to catch and rethrow:
function createService() {
const log = openFile("service.log");
let timer;
try {
timer = setInterval(() => {}, 1000);
return {
stop() {
clearInterval(timer);
log.close();
},
};
} catch (e) {
if (timer !== undefined) clearInterval(timer);
log.close();
throw e;
}
}
const service = createService();
service.stop();Now the cleanup logic exists twice, once in stop() and once in catch, and the two copies can drift apart. The DisposableStack.move() chapter returns to this pattern.
Summary of Failure Modes
| Failure mode | Cause | Symptom |
|---|---|---|
| Missing finally | Cleanup placed after code that can throw | Leak on error paths only |
| Partial acquisition | Second acquire runs outside any `try` | First resource leaks |
| Cleanup chain break | One `close()` throws in a shared `finally` | Later resources leak |
| Wrong order | Flat cleanup written in acquisition order | Dependent resource closed too early |
| Error masking | `finally` throws or returns | Original error lost |
| Unawaited async cleanup | `close()` called without `await` | Races, unhandled rejections |
| Duplicated cleanup | Ownership transfer with `catch` and rethrow | Two copies of the cleanup logic drift apart |
Every row comes from the same root cause. The language does not connect a resource's lifetime to a scope, so each programmer reconnects them by hand every time. The rest of this tutorial covers a feature that makes the connection declarative. You state at acquisition time that a value is a resource, and the runtime handles order, errors, and awaiting when the block exits.
Exercise
In copyFlat, list every way a resource can leak, naming which call has to throw for each one.
Show answer
If openFile(dest) throws, input leaks because no try protects it yet. If input.close() throws in the finally, output.close() never runs and output leaks. If the body throws, both closes run and nothing leaks, but a throwing input.close() would then also mask the body error.
Exercise
What does this code log, and why? function f() { try { return "body"; } finally { console.log("cleanup"); } } console.log(f());
Show answer
It logs "cleanup" and then "body". The return value is computed first, finally runs before the function actually returns, and then the caller receives "body". The finally would override that result only if it contained its own return or throw.
Exercise
Rewrite report() so that the connection is guaranteed to be closed before the returned promise resolves, and explain what the original version risked.
Show answer
Change the finally body to await conn.close();. The original called close() without awaiting it. report() therefore resolved while the close was still pending, so callers saw an open connection, and a rejection from close() would have been unhandled.