JavaScript Exceptions: throw, try/catch/finally, Error Types and Error Handling Patterns
How exceptions work in JavaScript: throwing Error objects, how an exception travels up the call stack, try/catch/finally in every combination, optional catch binding, the built-in error types, custom errors, error.cause, rethrowing, AggregateError, Error.isError, finally traps and async errors.
kvi5hnuCode Sprout team member8 min readOn this page
Programs fail in ways you can't always prevent: a file is missing, a server returns garbage, a user types letters into a number field, a bug reads a property of undefined. Exceptions are JavaScript's way of reporting such a failure: normal execution stops at the point of the error, and control jumps to the nearest code that has declared it can handle it. This article covers the whole mechanism and the patterns professionals use with it.
throw
throw expression; raises an exception. Execution of the current code stops immediately:
function parseAge(text) {
const age = Number(text);
if (!Number.isInteger(age) || age < 0) {
throw new RangeError(`invalid age: ${text}`);
}
return age;
}
try {
parseAge("abc");
} catch (err) {
console.log(err.name, "|", err.message);
console.log(err instanceof RangeError, err instanceof Error);
}
RangeError | invalid age: abc
true true
You can technically throw any value: a string, a number, an object. Don't. Throw Error objects (or subclasses), because only they carry a name, a message and a stack trace showing where the error happened, which is what makes debugging possible:
try {
throw "something broke";
} catch (err) {
console.log(typeof err, err.stack);
}
console.log(typeof new Error("m").stack);
string undefined
string
ESLint's no-throw-literal rule (and typescript-eslint's only-throw-error) flags throwing non-errors.
How an exception travels
When an exception is thrown, JavaScript looks for an enclosing try block with a catch in the current function. If there isn't one, the function ends immediately, and the search continues in the function that called it, and so on up the call stack. This is called propagation or unwinding. Any finally blocks along the way run as the exception passes through.

If no catch is found anywhere, the exception is uncaught: browsers log it to the console (and the rest of that script or event handler doesn't run), and Node.js prints it and exits with an error code.
This is the great strength of exceptions: the code that detects a problem (deep inside readUser) and the code that knows how to handle it (the UI in main) can be far apart, and nothing in between has to pass error codes along.
try/catch/finally
try { ... } catch (err) { ... } finally { ... }
trywraps code that might throw.catch (err)runs only if thetryblock threw;erris the thrown value, scoped to the catch block.finallyruns always: after thetrycompletes normally, after acatch, and even afterreturn,breakorcontinuejump out of thetry.
A try needs at least one of catch or finally, and the braces are mandatory even for one statement.
function attempt(shouldFail) {
const steps = [];
try {
steps.push("try");
if (shouldFail) throw new Error("boom");
steps.push("try finished");
} catch (err) {
steps.push(`catch: ${err.message}`);
} finally {
steps.push("finally");
}
steps.push("after");
return steps.join(" → ");
}
console.log(attempt(false));
console.log(attempt(true));
try → try finished → finally → after
try → catch: boom → finally → after
finally for cleanup
finally is where you release what the try acquired: close a file, hide a loading spinner, release a lock, re-enable a button. It runs no matter how the try ends:
function load() {
try {
return "data";
} finally {
console.log("spinner hidden");
}
}
console.log(load());
for (let i = 0; i < 2; i++) {
try {
if (i === 0) continue;
console.log("processing", i);
} finally {
console.log("finally for", i);
}
}
spinner hidden
data
finally for 0
processing 1
finally for 1
try/finally without a catch is common: clean up, but let the error continue up to someone who can handle it. For resources, ES2027's using declarations automate this pattern (part 13).
Don't return from finally
A return (or throw) inside finally replaces whatever the try or catch was doing, including an exception in flight, which is silently lost:
function overrides() {
try {
return "from try";
} finally {
return "from finally";
}
}
function swallows() {
try {
throw new Error("important failure");
} finally {
return "everything is fine";
}
}
console.log(overrides(), "|", swallows());
from finally | everything is fine
ESLint's no-unsafe-finally rule (in the recommended set) reports this. Keep finally blocks to cleanup.
Optional catch binding
If you don't need the error object, you can omit the parentheses (ES2019):
function isValidJson(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
console.log(isValidJson('{"a": 1}'), isValidJson("{bad"));
true false
The built-in error types
The engine throws these itself, and you can throw them too:
| Type | Thrown when | Example |
|---|---|---|
TypeError | a value has the wrong type for an operation | null.x, calling a non-function, assigning to a const |
ReferenceError | an identifier doesn't exist, or is in its TDZ | undeclaredName |
SyntaxError | code can't be parsed | eval("{"), JSON.parse("{bad") |
RangeError | a number is out of the allowed range | new Array(-1), (1).toFixed(200) |
URIError | malformed URI encoding | decodeURI("%") |
EvalError | code generation from strings is blocked (article 36) | rare |
AggregateError | several errors at once | Promise.any when all reject |
const failures = [
() => null.x,
() => undeclaredName,
() => JSON.parse("{bad"),
() => new Array(-1),
() => decodeURI("%"),
];
for (const fail of failures) {
try {
fail();
} catch (err) {
console.log(err.name);
}
}
TypeError
ReferenceError
SyntaxError
RangeError
URIError
Error messages differ between engines and versions (V8 says "Cannot read properties of null", Firefox says something else), so never write code that depends on the exact message text. Test err.name, instanceof, or a code property you control.
Custom error classes
For your own failure cases, extend Error. The subclass name lets callers tell your errors apart, and you can add fields with details:
class ValidationError extends Error {
constructor(field, message) {
super(message); // sets message and captures the stack
this.name = "ValidationError";
this.field = field;
}
}
try {
throw new ValidationError("email", "missing @");
} catch (err) {
console.log(err instanceof ValidationError, err.name, err.field);
console.log(String(err));
}
true ValidationError email
ValidationError: missing @
Set this.name, otherwise it's inherited as "Error". Classes are covered in part 9.
Wrapping errors with cause
When you catch a low-level error and throw a more meaningful one, keep the original as the cause (ES2022), so the full story survives for debugging:
function loadProfile() {
try {
throw new Error("ECONNRESET"); // what the network layer reported
} catch (err) {
throw new Error("could not load profile", { cause: err });
}
}
try {
loadProfile();
} catch (err) {
console.log(err.message, "← caused by:", err.cause.message);
}
could not load profile ← caused by: ECONNRESET
Node.js and browser consoles print the cause chain when logging the error.
Catching selectively and rethrowing
A catch clause catches everything thrown in its try: your expected error and also typos, TypeErrors from bugs, and anything else. JavaScript has no catch (ValidationError e) syntax, so check the type yourself and rethrow what you can't handle:
function save(data) {
if (!data.email) throw new RangeError("email required");
data.undefinedMethod(); // a bug
}
function trySave(data) {
try {
save(data);
return "saved";
} catch (err) {
if (err instanceof RangeError) return `invalid: ${err.message}`;
throw err; // not ours to handle
}
}
console.log(trySave({}));
try {
trySave({ email: "a@b.c" });
} catch (err) {
console.log("bug reached the top:", err.name);
}
invalid: email required
bug reached the top: TypeError
The anti-pattern to avoid is the empty catch, catch (err) {}, which hides bugs completely. If you really mean to ignore an error, write a comment saying why. ESLint's no-empty flags empty catch blocks.
Checking whether something is an error
instanceof Error fails for errors from another realm, such as an iframe or a Node vm context (article 33). ES2026 added Error.isError(value), which recognizes real error objects from anywhere and rejects look-alikes:
console.log(Error.isError(new TypeError("x")), Error.isError({ name: "Error", message: "fake" }));
true false
AggregateError: several failures at once
AggregateError holds a list of errors in its errors property. Promise.any throws one when every promise rejects, and you can create one when, say, validating a form produces several problems:
const problems = [new Error("name is empty"), new Error("age is negative")];
const err = new AggregateError(problems, "form has 2 errors");
console.log(err.name, err.message, err.errors.map((e) => e.message));
AggregateError form has 2 errors [ 'name is empty', 'age is negative' ]
Exceptions in asynchronous code
try/catch only catches errors thrown while its try block is running. A callback scheduled for later (with setTimeout, an event listener, or a .then callback) runs after the try has already finished, so the catch can't see its errors.
With async/await, the familiar syntax works again: await rethrows a rejected promise's reason at that point, inside the try:
async function fetchUser() {
throw new TypeError("bad response");
}
async function main() {
try {
await fetchUser();
} catch (err) {
console.log("caught:", err.name);
}
}
main();
caught: TypeError
Forgetting the await means the try finishes before the promise rejects, and the rejection goes unhandled. Part 13 covers promise rejections, unhandledrejection and Promise.allSettled.
When to throw, and when not to
- Throw when a function can't do its job and the caller can't reasonably continue as if nothing happened: invalid arguments, a broken invariant, an I/O failure.
- Don't throw for normal, expected outcomes. "No user found" from a search is a normal result: return
nullor an empty array. Exceptions are for exceptional situations, and catching them for ordinary control flow makes code hard to follow. - Validate early: check inputs at the boundary of your system (form handling, API responses) and throw or report there, so the rest of the code can trust its data.
- Catch where you can act: in the UI to show a message, in a request handler to send an error response, around a retryable operation to retry. Catching just to log and rethrow at every level only adds noise.
Common questions
Does try/catch make code slow?
Not in modern engines: code inside a try is optimized normally. Throwing is relatively expensive, because a stack trace is captured, which is one more reason not to use exceptions for ordinary control flow.
What is err in a catch block if I don't know what was thrown?
In JavaScript, it's whatever value was thrown, possibly not an Error at all (some libraries throw strings or plain objects). TypeScript types it as unknown for this reason. Check with err instanceof Error or Error.isError(err) before reading err.message.
Is the stack property standard?
stack has been implemented by every engine for years, but its format differs between them, and it's only now being standardized. Use it for logging and debugging, not for parsing.
Can I catch a SyntaxError in my own code?
Only when the code is parsed at run time: JSON.parse, eval, new Function, dynamic import() of a broken module. A syntax error in the script itself stops it from running at all, before any try exists.
Summary
throwstops execution and propagates up the call stack until acatchhandles it; uncaught errors are reported and stop that script or process.- Always throw
Errorobjects (or subclasses) forname,messageandstack. finallyalways runs; use it for cleanup, and neverreturnorthrowfrom it.- Built-in types:
TypeError,ReferenceError,SyntaxError,RangeError,URIError,EvalError,AggregateError. Test by type, never by message text. - Extend
Errorfor custom errors (setthis.name), wrap low-level errors with{ cause }, and useError.isErrorfor realm-safe checks. - Catch what you expect and rethrow the rest; never leave a catch block empty without a reason.
- With async code,
awaitinsidetryto catch rejections.
Practice Questions
What is logged?
let x = 1;
try {
x = 2;
throw 0;
} catch { x = 3; } finally {
x *= 10;
}
console.log(x);
Answer
30. The try sets 2 and throws, the catch sets 3, and finally multiplies by 10.
What does this code do when called?
function f() {
try {
return 1;
} finally {
console.log("done");
}
}
Answer
It logs "done" and then returns 1. finally runs after the return value has been computed but before the function actually returns. Because finally doesn't contain its own return, the value 1 is kept.
Why is this code fragile?
catch (err) {
if (err.message.includes("Cannot read")) ...
}
Answer
Error messages aren't standardized and differ between engines, browser versions and languages. Check err instanceof TypeError or, for your own errors, a name or code property.
Write a function that converts a string to an integer and throws a RangeError mentioning the input if it isn't an integer, and a TypeError if the argument isn't a string.
Answer
function toInt(text) {
if (typeof text !== "string") throw new TypeError("expected a string");
const n = Number(text);
if (!Number.isInteger(n)) throw new RangeError(`not an integer: ${text}`);
return n;
}
A try block contains this call. Does its catch run?
setTimeout(() => { throw new Error("late"); }, 0)
Answer
No. The callback runs later, after the try/catch has finished, so the error is uncaught. Handle errors inside the callback, or use promises and await so the error surfaces inside the try.
Previous: JavaScript Jump Statements: break, continue, Labels and return
Next: JavaScript Strict Mode, debugger and with: What "use strict" Changes

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.