JavaScriptFundamental (ES6), part 1
try...finally and return in JavaScript
132 try, finally, and a return that hijacks the answer
fairShow the four things finally does. It runs on the way out of a return; a return inside it replaces the value the try was going to give; that replacement also swallows an exception that was in flight; and a throw inside it replaces the outcome too. Then show that the returned expression is evaluated before finally runs, and what that means for an object.
Stuck? Three hints, smallest first
- 1. The value of
returnis computed first, thenfinallyruns, then the function actually returns. Reassigning the variable afterwards is too late. - 2. Too late for a variable, not for an object: the reference was already captured, so a property written in
finallyis visible to the caller. - 3. A
returninfinallycompletes the function, which is why an exception on its way out simply stops travelling.
const normal = () => {
try {
return 'from try';
} finally {
const noReturnHere = true;
}
};
const hijacked = () => {
try {
return 'from try';
} finally {
return 'from finally';
}
};
const swallowed = () => {
try {
throw new Error('boom');
} finally {
return 'finally ate the error';
}
};
const rethrown = () => {
try {
return 'never seen';
} finally {
throw new Error('finally threw instead');
}
};
let counter = 0;
const evaluatedFirst = () => {
try {
return counter;
} finally {
counter = 99;
}
};
const box = { n: 1 };
const mutatedAfter = () => {
try {
return box;
} finally {
box.n = 2;
}
};
const order = [];
const traced = () => {
try {
order.push('try');
return order.length;
} finally {
order.push('finally');
}
};
const cleanup = [];
const readRow = (bad) => {
cleanup.push('open');
try {
if (bad) throw new Error('bad row');
return 'ok';
} finally {
cleanup.push('close');
}
};
const captured = evaluatedFirst();
const returnedBox = mutatedAfter();
const tracedValue = traced();
const good = readRow(false);
let escaped = 'no error';
try { readRow(true); } catch (e) { escaped = e.message; }
let secondary = 'no error';
try { rethrown(); } catch (e) { secondary = e.message; }
console.log('values :', normal(), '|', hijacked(), '|', swallowed());
console.log('timing :', captured, '->', counter, '| box:', returnedBox.n);
console.log('cleanup:', cleanup, '| escaped:', escaped);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a finally that returns nothing leaves the value alone', normal(), 'from try');
test('a return inside finally replaces it', hijacked(), 'from finally');
test('and swallows an exception that was already on its way out', swallowed(), 'finally ate the error');
test('a throw inside finally replaces the outcome just as completely', secondary, 'finally threw instead');
test('the returned expression is evaluated before finally runs', [captured, counter], [0, 99]);
test('but a property written through the returned reference is visible', returnedBox.n, 2);
test('the block runs first, then finally, then the caller gets the value', [tracedValue, order], [1, ['try', 'finally']]);
test('finally runs on the throwing path too, and the error still escapes', [good, escaped], ['ok', 'bad row']);
test('so the cleanup happened both times', cleanup, ['open', 'close', 'open', 'close']);
finally is for releasing what you took: closing a handle, clearing a spinner, decrementing a counter. It runs on every way out — normal return, early return, thrown error, even a break out of a loop — which is exactly why it is the right place for that and the wrong place for anything that produces a value.
A return or throw inside finally completes the function then and there. The consequence is the third assertion: an exception that was travelling outward simply stops, with no catch anywhere, no log, and no trace. Most linters ban it for this reason, and if you ever meet a bug where an error "disappears", a return in a finally is the first thing to look for.
The timing pair is subtle and worth internalising. return counter evaluates counter immediately, so finally setting it to 99 changes nothing the caller sees. But return box captured a reference, so writing box.n in finally does reach the caller. Same rule, two different-looking outcomes, and the difference is only what was captured.