Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 42 of 58

Errors, try and catch

Handle runtime errors in JavaScript with try, catch and finally, throw your own errors, create custom error classes and know which errors to catch.

13 minClasses and errorsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonCatch and handle errors with try, catch and finally, throw your own errors, and write a custom error class.

After this lesson you can stop one failure from crashing a whole program. You will wrap risky code in try and catch, raise errors yourself with throw, and write your own error types.

What an error is

When JavaScript cannot carry on, it throws an error. If nothing catches it, the current script stops and the message appears in the console. Every error is an object with at least a name and a message. Here are some you will meet very soon:

javascript
JSON.parse("{bad");   // SyntaxError: Expected property name or '}' in JSON at position 1
null.x;               // TypeError: Cannot read properties of null (reading 'x')
undefinedVar;         // ReferenceError: undefinedVar is not defined
(1).toFixed(200);     // RangeError: toFixed() digits argument must be between 0 and 100

The wording of messages differs between browsers (those above come from Node, which uses the V8 engine as Chrome does), but the four names are standard. As a rough guide: a SyntaxError means text is not valid, a TypeError means a value is the wrong kind for what you did with it, a ReferenceError means a name does not exist, and a RangeError means a number is out of the allowed range.

try and catch

Put risky code in a try block. If something inside throws, JavaScript jumps straight to catch, with the error available as a variable.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  function parseAge(text) {
    const n = Number(text);
    if (Number.isNaN(n)) throw new TypeError(`"${text}" is not a number`);
    if (n < 0) throw new RangeError("Age cannot be negative");
    return n;
  }

  for (const text of ["42", "abc", "-3"]) {
    try {
      log("ok", parseAge(text));
    } catch (error) {
      log(error.name + ": " + error.message);
    } finally {
      log("checked", text);
    }
  }
</script>
result
ok 42
checked 42
TypeError: "abc" is not a number
checked abc
RangeError: Age cannot be negative
checked -3

Follow the three runs. For "42" nothing throws, so catch is skipped. For "abc", parseAge throws a TypeError; the rest of try is abandoned and catch runs. For "-3" the second throw fires. In every run, finally prints.

The three blocks have different jobs:

  • try holds the code that may fail.
  • catch handles the failure. You can write catch { without a variable when you do not need the error.
  • finally is optional and runs on every path, even when the try returns early. Use it for clean-up such as hiding a loading spinner.

throw

throw stops the function it is in and passes a value up to the nearest catch. Technically you can throw anything, even a string or a number, but always throw an Error object (or a subclass). Error objects carry a stack, a record of which functions were running, and you lose that if you throw a plain string. catch (e) receiving "just a string" has no .message and no .stack.

If no catch exists in the current function, the error travels up to whoever called it, then their caller, and on until something catches it or the script ends. This is useful: low-level code throws, and one catch near the top decides what to show the user.

Your own error types

A class that extends Error (see Inheritance with extends) lets you separate your own problems from everything else.

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

function validate(user) {
  if (!user.name) throw new ValidationError("Name is required", "name");
  return user;
}

for (const user of [{ name: "A" }, {}]) {
  try {
    validate(user);
    console.log("valid");
  } catch (error) {
    if (error instanceof ValidationError) {
      console.log("fix field", error.field, "-", error.message);
    } else {
      throw error; // not ours: pass it on
    }
  }
}
// valid
// fix field name - Name is required

Setting this.name makes the error print with your class name instead of plain Error. The instanceof check means only validation problems are handled here. Anything else, such as a genuine bug, is rethrown and stays visible.

Keeping the original cause

When you catch an error and throw a new, friendlier one, pass the old one as cause so nothing is lost:

javascript
try {
  try {
    throw new Error("inner");
  } catch (e) {
    throw new Error("outer", { cause: e });
  }
} catch (e) {
  console.log(e.message, "<-", e.cause.message); // outer <- inner
}

Return values and finally

A finally block runs even when the try already returned:

javascript
function f() {
  try { return "try"; }
  finally { console.log("cleanup"); }
}
console.log(f());
// cleanup
// try

The clean-up runs first, then the caller receives the value.

What try and catch cannot do

  • Syntax errors in your own file. If a bracket is missing, the browser refuses to run the file at all, so no try ever executes.
  • Errors in code that runs later. A try around setTimeout(() => risky(), 1000) finishes long before the timer fires, so it will not catch what happens inside. Put the try inside the callback. Promises and async and await have their own ways to handle failure.
  • A failed network request that returns a 404. fetch does not throw for HTTP error statuses. You will see this in Fetching data with fetch.

Common mistakes

  • An empty catch block. catch (e) {} swallows the problem, and you will spend hours wondering why nothing happens. At the very least log it.
  • Wrapping whole programs in one try. Wrap the small piece that can fail, so the catch knows what went wrong.
  • Using exceptions for normal flow. If you can check a condition with if, do that. Reserve throw for the truly unexpected.
  • Throwing strings. throw "bad" has no stack trace. Use throw new Error("bad").
  • Forgetting that catch also catches your typos. A misspelt variable inside try becomes a ReferenceError that your catch quietly handles as if it were a user problem. Check error.name or use instanceof.
  • Expecting finally to change the result. It is for clean-up. Avoid returning from it.

Exercise

Write safeParse(text) that calls JSON.parse(text) inside try. On success it returns the parsed value; on failure it returns null and logs the error's message. Test it with '{"a":1}', '{a:1}' and ''. Then change it so that, instead of returning null, it throws a new Error("Invalid JSON", { cause: error }), and catch that in the caller.

Next, learn how to find bugs when the code just does the wrong thing, in Debugging with the browser tools.

Key points

  • try runs code that might fail, catch runs only if it throws, and finally runs either way.
  • throw stops the current code and hands an error to the nearest catch; throw Error objects, not strings.
  • The common built-in types are SyntaxError, TypeError, ReferenceError and RangeError, and each has a name and message.
  • A custom class that extends Error lets you tell your own problems apart with instanceof.
  • Catch only what you can handle and rethrow the rest, because a catch that hides bugs makes them harder to find.

Check yourself

1. When does the finally block run?
2. Which statement raises an error of your own?
3. What error type does null.name give?
4. Inside a catch block you get an error you cannot deal with. What should you do?
5. Does try...catch catch a SyntaxError in the same script file, such as a missing bracket?