Error handling
try, catch, finally
JavaScript
try {
const data = JSON.parse("{not valid json}");
console.log(data);
} catch (err) {
console.log("Could not parse:", err.name, "-", err.message);
} finally {
console.log("finally always runs");
}
console.log("The program keeps going.");- Code in
tryruns until something throws. catchreceives the error object.finallyruns whether or not an error happened.
Common built-in errors
| Error | Typical cause |
|---|---|
ReferenceError | using a variable that doesn't exist |
TypeError | calling something that isn't a function, or reading a property of undefined |
SyntaxError | invalid code, or invalid JSON in JSON.parse |
RangeError | a number outside an allowed range |
JavaScript
const user = undefined;
try {
console.log(user.name);
} catch (err) {
console.log(err.constructor.name + ":", err.message);
}
console.log(user?.name ?? "no user"); // optional chaining avoids the errorThrowing your own errors
JavaScript
function withdraw(balance, amount) {
if (amount <= 0) throw new Error("Amount must be positive");
if (amount > balance) throw new RangeError(`Insufficient funds: balance is ${balance}`);
return balance - amount;
}
for (const amount of [50, -5, 500]) {
try {
console.log("New balance:", withdraw(200, amount));
} catch (err) {
console.log(`Refused (${err.name}): ${err.message}`);
}
}Always throw Error objects (not strings), so you get a name, a message and a stack trace.
Custom error classes
JavaScript
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function register(user) {
if (!user.email?.includes("@")) throw new ValidationError("email", "Email looks invalid");
return "registered";
}
try {
register({ email: "not-an-email" });
} catch (err) {
if (err instanceof ValidationError) {
console.log(`Fix the ${err.field} field: ${err.message}`);
} else {
throw err; // not ours: let it go up
}
}Checking instanceof lets you handle the errors you expect and re-throw everything else.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.