Error Handling
Things go wrong in every real program: a network request fails, a user types letters where you expected a number, saved data turns out to be corrupt. When JavaScript hits an error it stops the current code. try, catch and finally let you catch errors, recover gracefully and give the user a helpful message instead of a broken page.
What an error looks like
An uncaught error stops the script at that line and prints a red message in the console, like this one from trying to read a property of null:
const user = null;
console.log(user.name);
console.log("This line never runs");
The exact wording differs between browsers (Firefox says "user is null"), but the type, TypeError, is the same everywhere. Every error is an object with a name, a message and a stack (the chain of function calls that led to it). The built-in types you will meet most are:
| Type | Meaning | Example cause |
|---|---|---|
ReferenceError | A variable that doesn't exist | console.log(totl) (typo) |
TypeError | A value used in a way its type doesn't allow | null.name, calling something that isn't a function |
SyntaxError | Code or data that can't be parsed | A missing bracket, JSON.parse("{bad}") |
RangeError | A number outside the allowed range | new Array(-1), (5).toFixed(200) |
A SyntaxError in your own code is special: the browser finds it before running anything, so the whole script fails to start. try/catch can only catch errors that happen while code is running.
try and catch
Put risky code in a try block. If anything inside throws, JavaScript jumps straight to the catch block and hands it the error object. After the catch finishes, the program carries on normally.
try {
const user = null;
console.log(user.name);
console.log("skipped");
} catch (error) {
console.log("Something went wrong:", error.name);
}
console.log("The program continues");
If you don't need the error object, you can leave out the brackets: catch { ... }.
Throwing your own errors
Use throw when your code detects a problem it can't handle itself. Always throw an Error object (or one of its subtypes), not a plain string, so the catcher gets a message and a stack trace.
function withdraw(balance, amount) {
if (typeof amount !== "number" || Number.isNaN(amount)) {
throw new TypeError("Amount must be a number");
}
if (amount > balance) {
throw new RangeError(`Cannot withdraw KES ${amount}; balance is KES ${balance}`);
}
return balance - amount;
}
try {
console.log(withdraw(1000, 300));
console.log(withdraw(1000, 5000));
console.log(withdraw(1000, 100));
} catch (error) {
console.log(`${error.name}: ${error.message}`);
} finally {
console.log("Transaction closed");
}
The third withdraw never runs: the error from the second jumps straight to catch.
finally
A finally block runs no matter what: after try succeeds, after catch handles an error, and even if try contains a return. Use it for clean-up such as hiding a loading spinner or re-enabling a button.
function test() {
try {
return "from try";
} finally {
console.log("finally runs first");
}
}
console.log(test());
Handling different errors differently
Use instanceof to check what kind of error you caught. Handle the ones you expect, and re-throw anything else so real bugs aren't hidden. You can create your own error types with classes:
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function checkPhone(phone) {
if (phone.length !== 10) {
throw new ValidationError("phone", "Phone number must have 10 digits");
}
return true;
}
try {
checkPhone("07123");
} catch (error) {
if (error instanceof ValidationError) {
console.log(error.name, "on", error.field + ":", error.message);
} else {
throw error; // not ours to handle
}
}
When you catch one error and throw a clearer one, keep the original as the cause (supported in all modern browsers):
try {
try {
JSON.parse("{bad json}");
} catch (err) {
throw new Error("Could not read your saved settings", { cause: err });
}
} catch (error) {
console.log(error.message);
console.log("Caused by:", error.cause.name);
}
Errors in asynchronous code
A try/catch only covers code that runs while the try block is running. A callback that runs later is outside it:
try {
setTimeout(() => {
throw new Error("Too late!");
}, 100);
} catch (error) {
console.log("Caught?"); // never runs
}
By the time the timer fires, the try block finished long ago, so the error is uncaught. With promises, use .catch(); with async/await, put the await inside try, and a rejected promise is caught just like a normal error:
async function loadProfile() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const profile = await response.json();
console.log(profile.name);
} catch (error) {
console.log("Could not load profile:", error.message);
}
}
An empty catch {} that swallows errors silently. The program keeps going in a broken state and you have no clue why. At the very least log the error with console.error(error), and tell the user something useful ("Couldn't save. Check your connection and try again.").
Don't wrap everything in try/catch. Use it around operations that can fail for reasons outside your control: network requests, parsing outside data, storage and user input. A bug in your own logic is better fixed than caught.
Key points
- Errors are objects with
name,messageandstack; common types are TypeError, ReferenceError, SyntaxError and RangeError. tryruns risky code,catchhandles any error thrown, andfinallyalways runs.throw new Error("...")(or a subclass) signals problems; check types withinstanceofand re-throw what you can't handle.- For async code use
.catch()orawaitinsidetry; a callback that runs later isn't covered by an outertry.
Tip: use the ← and → keys to move between pages.
