JavaScriptadvanced 8 min
try, catch, finally and throw: handle problems without crashing, and raise your own errors.
How to catch errors with try / catch / finally, throw your own errors, and write messages that help you fix the problem.
Things go wrong: the network drops, a user types nonsense, a file is missing. A program that handles errors can recover or explain what happened, instead of crashing or silently doing the wrong thing.
When something goes wrong, JavaScript throws an error. If nothing catches it, the program stops. You catch errors like this:
err.name is the type (such as TypeError) and err.message is the description.throw new Error("Age must be positive").TypeError (wrong kind of value), ReferenceError (unknown variable), SyntaxError (bad code or bad JSON).Error, so callers can tell them apart with instanceof.finally is perfect for cleanup, such as hiding a loading spinner.ValidationError extends Error and sets its own name.parseAge throws a ValidationError for non-numbers and negative numbers."30" it returns 30 and prints age: 30. The finally block prints checked 30."abc", Number("abc") is NaN, so it throws. The catch prints invalid: Age must be a number, and finally still prints."-5", the second check throws: invalid: Age cannot be negative.throw err, so they are not hidden.SyntaxError, and we print its name.Add a rule that ages over 150 are invalid, and test it with "200".
catch block that hides problems. At least log the error.throw "oops"). Throw Error objects so you get a stack trace.try. Keep it around the risky lines.try / catch / finally handle problems; throw raises them.Error objects, and custom error classes to tell problems apart.You finished the JavaScript track. Try the practice exercises to lock it in.
try {
// code that might fail
} catch (err) {
// runs only if something above threw
} finally {
// always runs, success or not
}class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function parseAge(text) {
const age = Number(text);
if (Number.isNaN(age)) {
throw new ValidationError("Age must be a number");
}
if (age < 0) {
throw new ValidationError("Age cannot be negative");
}
return age;
}
for (const input of ["30", "abc", "-5"]) {
try {
console.log("age:", parseAge(input));
} catch (err) {
if (err instanceof ValidationError) {
console.log("invalid:", err.message);
} else {
throw err;
}
} finally {
console.log("checked", input);
}
}
try {
JSON.parse("{ bad json");
} catch (err) {
console.log(err.name);
}