Sub topic 1
Why Manual Cleanup Breaks: The try/finally Problem
Programs regularly acquire resources that must be released: file handles, database connections, locks, timers, event listeners. JavaScript has never tied that release to anything automatic. You write the cleanup yourself, usually in a finally block. This chapter shows where that habit breaks down and why tying cleanup to a scope is the safer model.
Prerequisites
This chapter assumes you are comfortable with:
- Block scoping with
letandconst try/catch/finallysemantics, including thatfinallyruns on return and throw- Promises and
async/await - ES classes and object literal methods
- Well-known symbols such as
Symbol.iterator
The single-resource case looks fine
With one resource, try/finally is readable enough:
function openResource(name) {
console.log(`open ${name}`);
return {
name,
close() {
console.log(`close ${name}`);
},
};
}
function readConfig() {
const file = openResource("config");
try {
return `read ${file.name}`;
} finally {
file.close();
}
}
console.log(readConfig());
// open config
// close config
// read configThe finally block runs whether the body returns or throws, so file.close() is always called. The cost is that the acquisition and the release sit far apart, and nothing forces you to write the finally in the first place.
Where it breaks
Multiple resources nest
Every extra resource needs its own try, because if the second acquisition throws, the first resource still has to be released:
function copy() {
const src = openResource("src");
try {
const dest = openResource("dest");
try {
return `copy ${src.name} -> ${dest.name}`;
} finally {
dest.close();
}
} finally {
src.close();
}
}
console.log(copy());Three resources mean three levels of nesting. Developers often flatten this into one try with several close() calls, which brings in the next bug.
Flattened cleanup leaks
function copyFlat() {
let src, dest;
try {
src = openResource("src");
dest = openResource("dest");
return "copied";
} finally {
dest.close(); // if this throws, src is never closed
src.close();
}
}If openResource("dest") throws, dest is undefined and dest.close() throws a TypeError. Then src.close() never runs, and the TypeError replaces the real error.
Cleanup errors hide the original error
An exception thrown inside finally silently replaces the one already in flight:
try {
try {
throw new Error("body failed");
} finally {
throw new Error("cleanup failed");
}
} catch (e) {
console.log(e.message); // "cleanup failed"; "body failed" is lost
}The real cause of the failure disappears from your logs.
Common mistakes at a glance
| Mistake | Consequence |
|---|---|
| Forgetting the `finally` | Resource leaks on any throw or early return |
| Closing in the wrong order | Dependent resource used after its parent closed |
| One `finally` for many resources | Later closes skipped when an earlier one throws |
| Throwing in `finally` | Original error discarded |
| Forgetting `await` on async close | Cleanup races with later code |
The underlying issue
The cleanup logic belongs to the resource, yet every caller has to re-implement it. The language never connects "this value was created in this block" with "release it when the block ends."
Scope-bound cleanup fixes this by making the release automatic. The resource says how to dispose of itself, the declaration binds it to a block, and the runtime disposes of it on every exit path, in reverse order, while keeping every error. The rest of this tutorial builds that model with Symbol.dispose, using, and await using.
Exercise
In copyFlat, openResource("dest") throws an Error("disk full"). Which error reaches the caller, and is src closed?
Show answer
The caller receives a TypeError, because dest is undefined when dest.close() runs in finally. That TypeError replaces "disk full", and src.close() never runs, so src leaks.
Exercise
Why is the nested try/finally version of copy correct when the flat version is not?
Show answer
Each resource gets its own finally, entered only after that resource was acquired successfully. Dest is closed before src, and a failure to acquire dest still runs src's finally.