demo · v131
file handle lifecycle: try/finally vs using
Open a mock file handle, throw a fake parse error mid-read, and watch what each style does. Left side uses try/finally — easy to forget. Right side uses using — disposal is guaranteed by the language. The simulator counts leaks so you can run it many times.
traditional try/finally (and one without)
using (deterministic dispose)
the api
function makeFile(name) {
return {
read() { /* ... */ },
[Symbol.dispose]() { console.log("closed", name); }
};
}
function read(name) {
using f = makeFile(name); // disposed at scope exit, even if read throws
return f.read();
}