Error Handling
try/catch/finally, the built-in Error types, throwing your own errors, and how to read a JavaScript error message.
finally always runs, and that includes its own return. A return inside finally replaces whatever the try or catch was doing, including an error that was in the middle of being thrown. The error simply vanishes: the caller gets a normal return value, nothing reaches any catch, and nothing is logged.
function saveOrder(order) {
try {
if (!order.items.length) throw new Error("order has no items");
return "saved";
} finally {
console.log("closing connection");
return "done"; // overrides the throw above
}
}
console.log(saveOrder({ items: [] }));
// closing connection
// done <- the "order has no items" error is goneWhen things go wrong — and how to handle it
Every program encounters errors: a user types something unexpected, a network request fails, a file doesn't exist. Without error handling, a single problem crashes the entire program. try/catch lets you catch errors and handle them gracefully — show a helpful message, try something else, or at least log what went wrong.
Reading a JavaScript error
Before you can handle errors, you need to read them. Open your browser console — every error has three key pieces:
// Uncaught TypeError: Cannot read properties of undefined (reading 'name')
// ↑ type ↑ what happened ↑ detail
// at getUserName (app.js:12)
// at main (app.js:25)
// ↑ stack trace — where in your code it happenedThe type tells you what category of error it is. The message tells you what went wrong. The stack trace tells you exactly which line caused it.
try / catch — catch an error and handle it
try {
// Code that might fail goes here
const data = JSON.parse("this is not valid JSON");
console.log(data.name);
} catch (error) {
// If anything in try throws an error, execution jumps here
console.error("Something went wrong:", error.message);
// The program continues normally after the catch block
}
console.log("Program keeps running");How it works:
- JavaScript runs the code inside
try { } - If an error occurs, it immediately jumps to
catch— no further lines in try run - The
errorvariable holds the Error object with.messageand.name - After catch, the program continues normally
finally — code that always runs
function readFile(filename) {
console.log("Opening file...");
try {
// Imagine this could fail:
if (!filename.endsWith(".txt")) {
throw new Error("Only .txt files are supported");
}
console.log("File read successfully");
return "file contents";
} catch (error) {
console.error("Error:", error.message);
return null;
} finally {
// This ALWAYS runs — whether try succeeded or catch ran
console.log("Closing file... (always happens)");
}
}
readFile("notes.txt"); // succeeds — finally still runs
readFile("image.png"); // fails — finally still runsThe example above uses finally the right way: for cleanup only, with the return statements in try and catch. Keep finally free of return (and of throw, which would replace the original error the same way), and the error carries on to the caller:
function saveOrder(order) {
try {
if (!order.items.length) throw new Error("order has no items");
return "saved";
} finally {
console.log("closing connection"); // cleanup only -- no return here
}
}
try {
console.log(saveOrder({ items: [] }));
} catch (e) {
console.log("caught:", e.message); // caught: order has no items
}throw — create your own errors
function setAge(age) {
if (typeof age !== "number") {
throw new TypeError("Age must be a number");
}
if (age < 0 || age > 150) {
throw new RangeError(`Age ${age} is not a valid age`);
}
return age;
}
try {
setAge("thirty"); // throws TypeError
} catch (e) {
console.error(e.name + ":", e.message);
// "TypeError: Age must be a number"
}
try {
setAge(200); // throws RangeError
} catch (e) {
console.error(e.name + ":", e.message);
// "RangeError: Age 200 is not a valid age"
}The built-in Error types
null.name "abc".sort()console.log(x) before declaring xnew Array(-1)decodeURI("%")Official Sources
- MDN Web Docs — Error
- MDN Web Docs — try...catch
- ECMAScript 2024 — The Error Object (§20.5)
- MDN Web Docs — AggregateError
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.