Error Handling
try/catch/finally, the built-in Error types, throwing your own errors, and how to read a JavaScript error message.
When 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 runsthrow — 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.