Skip to the content

Lesson 72 of 296

Errors: try, catch, finally and custom errors

What you will learn

  • What errors are and how to throw them
  • try, catch and finally
  • The Error object
  • Built-in error types
  • Creating custom error classes
  • Error causes and rethrowing
  • Good error-handling habits
On this page

Throwing errors

When something goes wrong that the code cannot handle, you throw an error. Throwing stops the current function and jumps to the nearest catch.

function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Insufficient funds");
  }
  return balance - amount;
}

You can throw any value, but always throw an Error object. It records a stack trace showing where the error happened.

try...catch...finally

try {
  const result = withdraw(50, 100);
  console.log(result);
} catch (error) {
  console.error(error.message);       "Insufficient funds"
} finally {
  console.log("Always runs");
}
BlockRuns
tryThe code that might fail
catchOnly if an error was thrown in try. Receives the error.
finallyAlways, whether there was an error or not, even if try or catch contains return

If you do not need the error object, you can write catch { ... } without brackets.

Use finally for cleanup: closing files, releasing database connections, hiding spinners.

The Error object

PropertyContains
nameThe error type, such as "TypeError"
messageThe description you gave
stackThe stack trace (file names and line numbers)
causeAn optional original error (below)

Built-in error types

TypeWhen it happens
SyntaxErrorCode is written incorrectly, or JSON.parse gets invalid JSON
ReferenceErrorUsing a variable that does not exist, or one in its TDZ
TypeErrorUsing a value the wrong way: calling something that is not a function, reading a property of undefined, assigning to const
RangeErrorA number outside the allowed range, such as new Array(-1) or a stack overflow
AggregateErrorSeveral errors together (from Promise.any)

Custom error classes

Custom errors let calling code tell different problems apart:

class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

class NotFoundError extends Error {
  constructor(resource) {
    super(`${resource} not found`);
    this.name = "NotFoundError";
  }
}

Using them:

try {
  saveUser(input);
} catch (error) {
  if (error instanceof ValidationError) {
    showFieldError(error.field, error.message);
  } else if (error instanceof NotFoundError) {
    showNotFoundPage();
  } else {
    throw error;      not ours: let it go up
  }
}

On a server, custom errors are often mapped to HTTP status codes: ValidationError to 400, NotFoundError to 404 (Part 15).

Error cause

When you catch a low-level error and throw a clearer one, keep the original with cause:

try {
  await db.query(sql);
} catch (err) {
  throw new Error("Could not save order", { cause: err });
}

Logs and debuggers can then show both errors.

Rethrowing

Only catch errors you can actually handle. If you cannot handle it, rethrow it so code higher up can deal with it, or so it reaches a central error handler.

Errors in async code

try...catch only catches errors from async work if you await it:

try {
  fetchData();              not awaited: rejection is NOT caught here
} catch {}

try {
  await fetchData();        caught
} catch {}

Errors thrown inside a callback that runs later (such as in setTimeout) are also not caught by a try...catch around the setTimeout call. The try block has already finished by then.

Global error handlers

As a safety net, log errors nobody caught:

  • Browser: window.addEventListener("error", ...) and window.addEventListener("unhandledrejection", ...).
  • Node.js: process.on("uncaughtException", ...) and process.on("unhandledRejection", ...). After an uncaught exception, log it and restart the process; the app may be in a broken state.

Production apps usually send errors to a monitoring service, such as Sentry, to see problems users meet.

Good habits

  • Never swallow errors: an empty catch {} hides bugs.
  • Fail early: check inputs at the start of a function and throw clear errors.
  • Give useful messages: "Order 1042 not found", not "Error".
  • Do not show internal details (stack traces, SQL) to users. Log them; show a friendly message.
  • Use errors for unexpected situations, not normal control flow.

Common mistakes

  • Throwing strings: throw "failed" has no stack trace.
  • Empty catch blocks.
  • Catching errors too early and losing information.
  • Expecting try...catch to catch un-awaited promise rejections.
  • Forgetting to set this.name in custom errors.

How to say it in an interview

"I throw Error objects so there is a stack trace, and catch them with try-catch, using finally for cleanup since it always runs. I create custom error classes extending Error, like ValidationError or NotFoundError, so callers can use instanceof to handle each case, and on the server I map them to status codes. I wrap lower-level errors with the cause option, rethrow what I cannot handle, never swallow errors, and remember that try-catch only catches async errors when the promise is awaited."

Key words

WordMeaning
ThrowRaise an error and stop the current code
try / catch / finallyRun code / handle errors / always clean up
Error objectAn object with name, message and stack
Stack traceThe list of calls that led to an error
Custom errorA class that extends Error for a specific problem
RethrowThrow a caught error again for higher code to handle
Swallow an errorCatch it and do nothing (a bad practice)

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.