Skip to content
Codewilds

Lesson 27 of 34 · Classes & Errors

JavaScript Error Handling: try, catch and Custom Errors

medium20 XP3 min read

Things go wrong. Users type letters where numbers belong, files are missing, servers go down and JSON arrives broken. Professional code doesn't pretend errors never happen. It expects them, handles them where it makes sense and reports them clearly everywhere else.

In this lesson you'll learn how JavaScript errors work, how to catch them, how to throw your own, and how to create custom error types that make bugs easy to diagnose.

What an error looks like

When something goes wrong at runtime, JavaScript throws an error object. If nothing catches it, the program stops:

const hero = null;
console.log(hero.name); // TypeError: Cannot read properties of null (reading 'name')

Every error has a name (the kind of error) and a message (what happened). You've already met a few built-in kinds:

  • ReferenceError: using a variable that doesn't exist.
  • TypeError: using a value the wrong way, like calling something that isn't a function.
  • RangeError: a number outside the allowed range.
  • SyntaxError: invalid code, or invalid JSON passed to JSON.parse.

try and catch

Code that might fail goes in a try block. If an error is thrown inside it, JavaScript jumps straight to the catch block, where you receive the error object:

try {
  const data = JSON.parse("{ broken json");
  console.log(data);
} catch (error) {
  console.log(error.name);         // SyntaxError
  console.log("Could not load the save file.");
}
console.log("The program keeps running!");

If you don't need the error object, you can leave out the parentheses: catch { ... }.

finally

A finally block runs no matter what: after try succeeds, after catch handles an error, even after a return. It's the place for cleanup like closing connections or hiding a loading spinner:

try {
  console.log("Loading...");
} finally {
  console.log("Done loading."); // always runs
}

Throwing your own errors

Use throw to signal that something is wrong. Always throw an Error object (or a subclass), never a plain string, because Error objects carry a name, a message and a stack trace:

function setVolume(level) {
  if (level < 0 || level > 10) {
    throw new RangeError(`Volume must be 0-10, got ${level}`);
  }
  return level;
}

Throw when your function can't do its job. The caller then decides how to recover.

Custom error classes

For errors that are specific to your program, extend Error. Custom errors can carry extra data, and callers can recognise them with instanceof:

class QuestError extends Error {
  constructor(message, questId) {
    super(message);          // sets this.message
    this.name = "QuestError";
    this.questId = questId;
  }
}

try {
  throw new QuestError("The dragon is asleep", 42);
} catch (error) {
  if (error instanceof QuestError) {
    console.log(`Quest ${error.questId} failed: ${error.message}`);
  } else {
    throw error; // not ours: let someone else deal with it
  }
}

Notice the else { throw error; }. Catch the errors you know how to handle, and rethrow the rest. Silently swallowing unknown errors hides real bugs.

Common mistakes

  • Empty catch blocks. catch {} with nothing inside makes bugs invisible. At least log the error, or rethrow it.
  • Throwing strings. throw "oops" has no name or stack trace. Use throw new Error("oops").
  • Wrapping everything in try/catch. Only catch where you can actually do something useful.
  • Forgetting this.name in a custom error. Without it, your error is reported as a plain Error.

Assignment

  1. Complete the class InsufficientGoldError, which extends Error. Its constructor takes (needed, available), and the error must have:
    • message: "Need <needed> gold, but only have <available>"
    • name: "InsufficientGoldError"
    • properties needed and available
  2. Write buyItem(gold, price), which returns the gold left after buying:
    • If price is zero or negative, throw a RangeError with the message "Price must be positive".
    • If price is more than gold, throw an InsufficientGoldError.
    • Otherwise return gold - price.
  3. Write safeParse(json, fallback), which returns JSON.parse(json), or fallback if the text isn't valid JSON. fallback defaults to null.
buyItem(100, 30); // 70
buyItem(20, 50);  // throws InsufficientGoldError: Need 50 gold, but only have 20
safeParse('{"a":1}');  // { a: 1 }
safeParse("oops");     // null

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Errors and exceptions in other languages

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 27 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.