Things go wrong in every real program: a user types letters where a number belongs, a server is down, a value turns out to be null. Without error handling, one of these problems stops your script completely. With try...catch you can catch the error, show a useful message and keep the page working. You can also throw your own errors to reject bad input clearly.
In this lesson you will learn
- How
try,catchandfinallywork - Throwing errors with
throw new Error() - Built-in error types such as
TypeErrorandRangeError - Creating custom error classes
- When to catch and when to let an error through
try, catch, finally and throw
function parseAge(text) {
const age = Number(text);
if (Number.isNaN(age)) {
throw new TypeError(`"${text}" is not a number`);
}
if (age < 0 || age > 150) {
throw new RangeError(`Age ${age} is out of range`);
}
return age;
}
for (const input of ["21", "abc", "-5"]) {
try {
console.log("Valid age:", parseAge(input));
} catch (err) {
console.log(`${err.name}: ${err.message}`);
} finally {
console.log(" checked", JSON.stringify(input));
}
}
try {
const user = null;
console.log(user.name);
} catch (err) {
console.log("Caught:", err.constructor.name);
}
Output
Valid age: 21
checked "21"
TypeError: "abc" is not a number
checked "abc"
RangeError: Age -5 is out of range
checked "-5"
Caught: TypeError
- Code inside
tryruns normally. If anything in it throws, JavaScript jumps straight tocatch, skipping the rest of thetryblock. - The
catch (err)block receives the error object.err.nameis its type anderr.messageis the description. finallyruns every time, whether or not there was an error. It is the place for clean-up such as hiding a loading spinner or closing a file.throwraises your own error. Throw anErrorobject (or a subtype) rather than a plain string, so that the name, message and stack trace are available.- JavaScript also throws errors itself: reading a property of
nullproduces aTypeError.
Custom Error Classes
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", "Please enter a valid email");
}
if ((user.password ?? "").length < 8) {
throw new ValidationError("password", "Password needs at least 8 characters");
}
return `Registered ${user.email}`;
}
const attempts = [
{ email: "nila.example.com", password: "secret123" },
{ email: "nila@example.com", password: "short" },
{ email: "nila@example.com", password: "longenough" },
];
for (const a of attempts) {
try {
console.log(register(a));
} catch (err) {
if (err instanceof ValidationError) {
console.log(`Field "${err.field}": ${err.message}`);
} else {
throw err; // unexpected errors should not be hidden
}
}
}
Output
Field "email": Please enter a valid email
Field "password": Password needs at least 8 characters
Registered nila@example.com
ValidationErrorextends the built-inErrorclass and adds afieldproperty, so the code that catches it knows which form field to highlight.instanceoflets thecatchblock handle only the errors it understands.- Any other error is re-thrown with
throw err. Silently swallowing unexpected errors hides bugs and makes them very hard to find.
Built-in Error Types
| Type | Typical cause |
|---|---|
ReferenceError | Using a variable that does not exist |
TypeError | Calling something that is not a function, or reading a property of null/undefined |
SyntaxError | Invalid code, or JSON.parse on bad text |
RangeError | A number outside the allowed range, such as new Array(-1) |
A SyntaxError in your own source code cannot be caught by that same code, because the script never starts running. try...catch only handles errors that happen while code runs.
Common Mistakes
- Empty catch blocks that hide every problem. At least log the error.
- Wrapping huge blocks of code in one try, so you cannot tell what failed. Keep try blocks small.
- Throwing strings:
throw "oops"has no stack trace or name. - Expecting try/catch to catch errors in a callback that runs later, such as inside
setTimeout. Use async/await or handle errors inside the callback.
Practice Exercises
Exercise 1. Write safeParse(text) that returns the parsed JSON, or null if the text is invalid.
Show answer
function safeParse(text) {
try {
return JSON.parse(text);
} catch {
return null;
}
}
console.log(safeParse('{"a":1}'), safeParse("{bad"));
When you do not need the error object, the parameter after catch can be left out.
Exercise 2. Write divide(a, b) that throws a RangeError when b is 0.
Show answer
function divide(a, b) {
if (b === 0) throw new RangeError("Cannot divide by zero");
return a / b;
}
Frequently Asked Questions
Does dividing by zero throw an error in JavaScript?
No. 5 / 0 gives Infinity and 0 / 0 gives NaN. If that should count as an error in your program, check for it and throw yourself.
What is err.stack?
It is a text trace of the function calls that led to the error, with file names and line numbers. It is the most useful thing to log when debugging.
Summary
tryruns risky code,catchhandles the error,finallyalways runs.throw new Error("message")signals a problem; use specific types where they fit.- Custom error classes carry extra details; check them with
instanceof. - Handle what you understand and re-throw the rest.
Next: Promises and async/await.
