throw, catch, finally and What Escapes
Throwing unwinds the stack until something catches, and finally runs on the way past whatever happens.
throw accepts any value and should be given an Error. catch stops the unwinding. finally runs on success, on failure and on return, which makes it the place for cleanup. A return inside finally silently discards whatever was being returned or thrown.
EXERCISE
1What Throwing Actually Does
An exception is not a return value. It unwinds the call stack, abandoning every frame until one of them is willing to stop it.
The unwinding, made visible:
function level3() {
console.log("3 start");
throw new Error("boom");
console.log("3 end"); // never runs
}
function level2() {
console.log("2 start");
level3();
console.log("2 end"); // never runs
}
function level1() {
console.log("1 start");
try {
level2();
} catch (err) {
console.log("1 caught:", err.message);
}
console.log("1 end");
}
level1();
// 1 start
// 2 start
// 3 start
// 1 caught: boom
// 1 end
level2 had more work to do and never did it. It was not asked; its frame was discarded. That is what separates an exception from a returned error code, and it is why a throw in the middle of a function leaves anything after it undone.
You can throw any value, and should not:
throw "something failed"; // legal
throw 42; // legal
throw { code: 500 }; // legal
throw new Error("something failed"); // the one to write
An Error carries a message, a name and a stack recording where it came from. A thrown string carries none of that, so a failure five layers down arrives with no indication of where it started.
It also breaks the checks everyone writes:
try {
throw "oops";
} catch (err) {
console.log(err.message); // undefined
console.log(err instanceof Error); // false
console.log(err.stack); // undefined
}
catch can omit the binding when you do not need it:
try {
return JSON.parse(input);
} catch {
return null;
}
Useful when the only thing that matters is that it failed. Say so deliberately rather than writing catch (err) and ignoring err, which reads like an oversight.
And a rethrow keeps the failure travelling:
try {
risky();
} catch (err) {
console.log("logging:", err.message);
throw err; // still failing, now recorded
}
Catching only to log, then rethrowing, is a legitimate pattern. Catching only to log and not rethrowing turns a failure into silence, which is the single most damaging thing you can do in an error handler.
Throw Error objects, always, including in code you think nobody will see. The stack is what turns a five-minute session into a five-second one, and it is created at the moment of construction, so you cannot add it back later.
EXERCISE
2finally, and the Trap Inside It
finally runs on every path out of a try block, which makes it reliable for cleanup and dangerous for anything else.
It runs on success, on failure, and on return:
function read() {
try {
return "value";
} finally {
console.log("cleanup");
}
}
console.log(read());
// cleanup
// value
The return value was computed, then finally ran, then the value was returned. finally genuinely runs on the way out, not instead of the exit.
Which makes it the right place for releasing anything:
async function withConnection(work) {
const connection = await pool.acquire();
try {
return await work(connection);
} finally {
connection.release(); // on success, on throw, on early return
}
}
No catch at all here. The function does not want to handle failures, only to guarantee the connection goes back. Failures pass straight through to the caller, which is usually correct.
The trap: a return inside finally overrides everything.
function broken() {
try {
return "from try";
} finally {
return "from finally";
}
}
console.log(broken()); // from finally
Worse, it swallows exceptions:
function worse() {
try {
throw new Error("important failure");
} finally {
return "everything is fine";
}
}
console.log(worse()); // everything is fine
// The error is gone. No trace, no log, nothing.
An error was raised and silently discarded because finally returned. This is one of the few genuinely dangerous constructs in the language, and linters flag it for good reason.
The same applies to throwing from finally:
function alsoBad() {
try {
throw new Error("original");
} finally {
throw new Error("replacement"); // original is lost
}
}
So the rule is short:
// finally should perform side effects and nothing else.
// No return. No throw. No break or continue out of it.
One more case worth seeing: finally with no catch.
function attempt() {
try {
return risky();
} finally {
console.log("attempted");
}
}
If risky throws, attempted is logged and the error continues to the caller. finally does not catch anything; it only guarantees a visit on the way past.
Pro Tip: Use
try/finallywith nocatchwhenever you must release something but have no business handling the failure. It is an underused shape: it makes the cleanup guaranteed and leaves error handling to whoever actually knows what to do, rather than forcing you to catch and rethrow.
EXERCISE
3When Not to Throw
An exception is for the exceptional. A failure you expect is often better returned than thrown.
Throwing is the right tool when a function genuinely cannot continue and the caller almost certainly cannot either. It is the wrong tool for outcomes you expect.
A failure that is not exceptional:
function parseAge(input) {
const n = Number(input);
if (Number.isNaN(n)) {
throw new Error("not a number");
}
return n;
}
Bad input from a form is not exceptional; it is the normal case half the time. Every caller now needs a try block for something that was always going to happen, and the cost of building a stack trace is paid on a completely ordinary path.
Returning the outcome instead:
function parseAge(input) {
const n = Number(input);
return Number.isNaN(n)
? { ok: false, error: "Age must be a number" }
: { ok: true, value: n };
}
const result = parseAge(form.age);
if (!result.ok) {
showFieldError("age", result.error);
return;
}
use(result.value);
The failure is part of the function's signature rather than hidden behind it. A reader can see both outcomes without reading the body, and there is no invisible control flow.
The built-ins already make this distinction:
"abc".indexOf("z"); // -1, does not throw
[1, 2].find((n) => n > 5); // undefined, does not throw
new Map().get("missing"); // undefined, does not throw
JSON.parse("{ bad }"); // throws: the input was supposed to be valid
null.foo; // throws: this is a programming mistake
Not finding something is normal. Being handed something that violates a contract is not. That line is the whole distinction, and the built-ins have been drawing it consistently for decades.
A rough test:
// Will the caller almost always want to handle this specifically?
// -> return it
//
// Does this mean a bug, or that continuing would be wrong?
// -> throw it
And the middle ground, for parsing:
function tryParse(json) {
try {
return { ok: true, value: JSON.parse(json) };
} catch (err) {
return { ok: false, error: err.message };
}
}
Catching at the boundary and converting to a value is how you adapt a throwing into one that fits the expected-failure style. This shape has a name in other languages, Result or Either, and it is worth recognising even though has no built-in version.
