Error Handling in JavaScript With try catch and finally
try runs code, catch handles a thrown value and finally always runs, even after return. See rethrowing, finally overrides and what try cannot catch.

Error handling code has two ways to go wrong, and they pull in opposite directions. A catch block that swallows everything hides bugs for months, and a missing catch crashes a process on the first bad input. The statement itself is simple, and the details that cause trouble are about what finally does with a return, what try cannot reach, and what to do with an error you do not know how to handle. This post covers each with runnable output on Node.js 24, and ends with the rules we apply. The error values you throw are the subject of the post on custom error classes, and the async side is part of the guide to how JavaScript runs.
The three clauses
A try needs a catch, a finally, or both. Control passes to catch when something in the try throws, and finally runs at the end in every case.
function parseConfig(text) {
const log = [];
try {
log.push("parsing");
const value = JSON.parse(text);
log.push("parsed");
return { value, log };
} catch (error) {
log.push("caught " + error.name);
return { value: null, log };
} finally {
log.push("finally");
}
}
console.log(parseConfig('{"port": 8080}'));
console.log(parseConfig("not json"));{ value: { port: 8080 }, log: [ 'parsing', 'parsed', 'finally' ] }
{ value: null, log: [ 'parsing', 'caught SyntaxError', 'finally' ] }In the success case the try returned, and finally still ran afterward, though the log is read after the return value was computed. In the failure case JSON.parse threw a SyntaxError, control jumped to catch, and finally ran last. The log.push("parsed") line never executed in the second case, because the throw skipped the rest of the try block.
What a thrown error looks like
catch receives whatever was thrown. For built-in failures that is an Error subclass with a name and message.
const failures = [
() => JSON.parse("{bad"),
() => null.property,
() => undefinedVariable,
() => new Array(-1),
() => decodeURIComponent("%"),
() => BigInt("1.5"),
];
for (const run of failures) {
try {
run();
} catch (error) {
console.log(error.name.padEnd(15), error.message);
}
}SyntaxError Expected property name or '}' in JSON at position 1 (line 1 column 2)
TypeError Cannot read properties of null (reading 'property')
ReferenceError undefinedVariable is not defined
RangeError Invalid array length
URIError URI malformed
SyntaxError Cannot convert 1.5 to a BigIntEach built-in error type signals a kind of failure: SyntaxError for text that cannot be parsed, TypeError for a value of the wrong type, ReferenceError for an unknown name, RangeError for an out-of-range number and URIError for a bad escape sequence. The messages come from the engine and can differ between runtimes, so code should branch on the type and not on message text.
finally and return
A finally block runs even when the try returns. If the finally block itself returns, it replaces the earlier return value and silently swallows any thrown error.
function normal() {
try {
return "from try";
} finally {
console.log("cleanup ran");
}
}
function overridden() {
try {
return "from try";
} finally {
return "from finally";
}
}
function swallowing() {
try {
throw new Error("lost");
} finally {
return "no error visible";
}
}
console.log(normal());
console.log(overridden());
console.log(swallowing());cleanup ran
from try
from finally
no error visibleThe first function ran its cleanup and returned the try value. The second returned the finally value, and the third hid the thrown error entirely. A return, break or continue inside finally is almost always a mistake, and the no-unsafe-finally ESLint rule reports it. Keep finally for cleanup that does not decide the result.
Rethrowing what you cannot handle
A catch that handles one kind of error should pass the rest on. Swallowing everything is how a bug turns into silence.
class NotFoundError extends Error {}
function lookup(id) {
if (id === 0) throw new NotFoundError("no such record");
if (id < 0) throw new RangeError("id must be positive");
return { id };
}
function find(id) {
try {
return lookup(id);
} catch (error) {
if (error instanceof NotFoundError) {
return null;
}
throw error;
}
}
console.log(find(5));
console.log(find(0));
try {
find(-1);
} catch (error) {
console.log("escaped:", error.name, error.message);
}{ id: 5 }
null
escaped: RangeError id must be positiveThe missing record was an expected outcome and became null. The invalid id was a bug in the caller, so the catch rethrew it and it reached the outer handler with its stack intact. Writing throw error and not throw new Error(error.message) preserves the original stack and type. If you want to add context, wrap with a cause, as covered in the post on custom errors.
Optional catch binding
If you do not need the error value, you can omit the binding. The syntax is allowed since ES2019.
function safeParse(text, fallback) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
console.log(safeParse("[1,2]", []));
console.log(safeParse("oops", []));[ 1, 2 ]
[]Use this only when the failure really carries no information you need. A parse fallback for optional user input is a fair case, and a catch that discards an error from a database call is not.
Async code: what try can and cannot catch
try works with await, because an awaited rejection is rethrown at the await. It does not catch an error from a promise you did not await, or from a callback that runs after the try has finished.
const delay = (ms, fail) =>
new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error("late failure")) : resolve("ok")), ms));
async function awaited() {
try {
await delay(1, true);
} catch (error) {
return "caught: " + error.message;
}
}
async function notAwaited() {
const pending = delay(1, true);
try {
pending;
return "try finished first";
} catch (error) {
return "never reached";
} finally {
pending.catch(() => {});
}
}
console.log(await awaited());
console.log(await notAwaited());
try {
setTimeout(() => {
throw new Error("thrown later");
}, 0);
} catch {
console.log("never printed");
}
process.once("uncaughtException", (error) => {
console.log("uncaughtException:", error.message);
});
await delay(20, false);caught: late failure
try finished first
uncaughtException: thrown laterThe awaited call was caught. The second function left the promise unattended, so its try finished, the error was never seen by the catch, and we had to attach a handler to the promise in the finally to stop it crashing the process. The timer throw happened after the try had ended, and Node.js reported it as an uncaught exception, which the demo intercepts. The rule is that try guards only the call stack it is on. The post on forEach() and await covers the loop version of this trap.
What you can throw
The language lets you throw any value, and the only good choice is an Error.
function describeThrown(value) {
try {
throw value;
} catch (caught) {
return {
isError: caught instanceof Error,
hasStack: typeof caught?.stack === "string",
message: caught?.message,
};
}
}
console.log(describeThrown(new Error("real")));
console.log(describeThrown("a string"));
console.log(describeThrown({ code: 7 }));
console.log(describeThrown(undefined));{ isError: true, hasStack: true, message: 'real' }
{ isError: false, hasStack: false, message: undefined }
{ isError: false, hasStack: false, message: undefined }
{ isError: false, hasStack: false, message: undefined }A string or an object has no stack trace, so the place the error came from is lost, and a catch that reads error.message gets undefined. Throwing undefined is legal and leaves nothing to catch. Because third-party code can throw anything, a defensive catch should check error instanceof Error before reading properties.
Cleanup with finally
finally is the right place to release things: close a file, release a lock, clear a timer. It runs on every exit path, including exceptions that are not caught.
function withLock(lock, work) {
lock.held = true;
try {
return work();
} finally {
lock.held = false;
}
}
const lock = { held: false };
console.log(withLock(lock, () => "done"), lock.held);
try {
withLock(lock, () => {
throw new Error("work failed");
});
} catch (error) {
console.log(error.message, lock.held);
}done false
work failed falseThe lock was released both after a normal return and after a failure, and the error still propagated to the caller. The newer using declaration, covered in the post on explicit resource management, expresses the same guarantee with less ceremony for objects that implement a disposal method.
Rules we apply
Catch at the place that can do something about the failure, not at every call. Check the type, handle what you know, and rethrow the rest. Throw Error instances, with cause when you wrap. Keep finally free of return. In async code, await inside the try, or attach a handler. And log an error once, at the point where it is handled, so a failure does not produce five copies in the logs.
Testing the error paths
Error handling is the code that runs least often, so it needs tests that force it to run. Assert both the type and the behavior, and test that unexpected errors are rethrown and not swallowed, since that is the property most often broken by a later edit.
import { test } from "node:test";
import assert from "node:assert/strict";
function readPort(text) {
try {
return JSON.parse(text).port;
} catch (error) {
if (error instanceof SyntaxError) return 3000;
throw error;
}
}
test("invalid JSON falls back to the default", () => {
assert.equal(readPort("oops"), 3000);
});
test("a missing object is not hidden", () => {
assert.throws(() => readPort("null"), TypeError);
});
test("a valid port is returned", () => {
assert.equal(readPort('{"port": 8080}'), 8080);
});Run it with node --test on Node.js 24. The second test is the valuable one: JSON.parse("null") succeeds and returns null, and reading .port throws a TypeError, which is not a SyntaxError and must pass through. A catch that handled every error would have returned 3000 and hidden the problem.
Where try and catch stop being the answer
For expected, frequent outcomes such as a missing record or invalid input, a return value like null or a result object is clearer and cheaper than an exception. Reserve throwing for conditions the caller did not plan for. For a program that must survive any error in a long-running process, add a top-level handler for uncaughtException and unhandledRejection that logs and exits cleanly, since continuing in an unknown state is rarely safe.
The statements are defined in the specification under the try statement, and MDN's page on try...catch covers the details.


