Reading history

JavaScript Error Handling: try, catch, finally and throw

5 min read 0 views

Learn JavaScript error handling: try, catch and finally, throwing errors, TypeError and RangeError, and custom error classes.

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, catch and finally work
  • Throwing errors with throw new Error()
  • Built-in error types such as TypeError and RangeError
  • 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 try runs normally. If anything in it throws, JavaScript jumps straight to catch, skipping the rest of the try block.
  • The catch (err) block receives the error object. err.name is its type and err.message is the description.
  • finally runs 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.
  • throw raises your own error. Throw an Error object (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 null produces a TypeError.

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
  • ValidationError extends the built-in Error class and adds a field property, so the code that catches it knows which form field to highlight.
  • instanceof lets the catch block 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

TypeTypical cause
ReferenceErrorUsing a variable that does not exist
TypeErrorCalling something that is not a function, or reading a property of null/undefined
SyntaxErrorInvalid code, or JSON.parse on bad text
RangeErrorA 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

  1. Empty catch blocks that hide every problem. At least log the error.
  2. Wrapping huge blocks of code in one try, so you cannot tell what failed. Keep try blocks small.
  3. Throwing strings: throw "oops" has no stack trace or name.
  4. 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

  • try runs risky code, catch handles the error, finally always 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.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *