throw for Custom Errors

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Raising Your Own Error with throw

Suppose you write a `heal(hp, amount)` function, and someone calls it with a negative number (`-30`). JavaScript sees nothing wrong with `50 + (-30)`, so the Codémon silently loses HP instead of healing:

function heal(hp, amount) { return hp + amount; } console.log(heal(50, -30));

JavaScript doesn't know the rules of your game — you do! The `throw` keyword lets you raise an error yourself as soon as a rule is broken:

function heal(hp, amount) { if (amount < 0) { throw new Error("Heal amount cannot be negative"); } return hp + amount; } console.log(heal(50, 30)); console.log(heal(50, -30)); // error!

Now `heal(50, -30)` stops immediately with your custom error message, right where the mistake happened!

Exercise 2 — Anatomy of throw

throw new Error("What went wrong");

1. `new Error(...)` — Creates an error object whose `.message` property is the string you passed. 2. `throw` — Triggers that error immediately. Just like `return`, the current function stops on the spot, and any lines after `throw` are skipped. 3. The error travels up to the nearest `catch` block (or crashes the program in red if there is no `catch`).

function check(level) { if (level > 100) { throw new Error("Level too high"); } console.log("Level " + level + " accepted"); } check(50); try { check(999); console.log("This line never runs"); } catch (error) { console.log("Caught: " + error.message); }

Exercise 3 — throw and catch Work Together

Now the two halves of error handling fit together: - A function uses `throw` when it detects an invalid input. - The code that called the function uses `try...catch` to handle the refusal gracefully.

function buy(gold, price) { if (price > gold) { throw new Error("Not enough gold"); } return gold - price; } let gold = 100; try { gold = buy(gold, 30); console.log("Bought! Gold left: " + gold); gold = buy(gold, 500); console.log("Bought again!"); } catch (error) { console.log("Purchase refused: " + error.message); } console.log("Final gold: " + gold);

The first purchase (`30`) succeeds and updates `gold` to `70`. The second purchase (`500`) throws an error, jumps straight to `catch`, and leaves `gold` safely at `70`!

Exercise 4 — Quiz: What Gets Printed?

What does this code print?

function f(x) { if (x < 0) { throw new Error("negative"); } return "ok"; } try { console.log(f(-1)); } catch (error) { console.log(error.message); }
Options
• negative
• ok
• Error
• A crash

Hint : The thrown message travels to the nearest catch.

Exercise 5 — Quiz: After the throw

What does this code print?

function f() { console.log("A"); throw new Error("stop"); console.log("B"); } try { f(); } catch (error) { console.log("C"); }
Options
• A, C
• A, B, C
• A only
• C only

Hint : A throw ends the function immediately, like a return would.

Exercise 6 — Refuse Negative Damage

Make the function raise an error when the damage is negative.

Hint : One keyword launches the alarm, and the built-in object that carries a message has a short name.

Exercise 7 — Validate Early, Validate Clearly

The best place to `throw` is at the very top of a function, before any real work begins. Checking your inputs right at the start (often called guard clauses) guarantees that the rest of the function can trust its data completely:

function createCodemon(name, level) { if (name === "") { throw new Error("Name cannot be empty"); } if (level < 1 || level > 100) { throw new Error("Level must be between 1 and 100"); } return { name: name, level: level }; } const zap = createCodemon("Zap", 5); console.log(zap.name + " Lv." + zap.level); try { createCodemon("", 5); } catch (error) { console.log("Refused: " + error.message); }

Write messages for humans

A good error message states which rule was broken and what was expected: `"Level must be between 1 and 100"` is much more helpful than `"bad input"`!

Exercise 8 — Quiz: Nobody Catches It

A function throws an error and no `try...catch` exists anywhere in the program. What happens?

Options
• The program crashes and shows the message
• The error is silently ignored
• The function returns undefined
• The program restarts

Hint : A thrown error keeps travelling up until something catches it, or nothing does.

Exercise 9 — Guard the Level

Refuse any level above 100 with a clear message.

Hint : The rule is broken when the level goes beyond the limit, and the caught object carries the explanation in one property.

Exercise 10 — throw Cheat Sheet

Match each element with its role.

Items to match
• new Error("...")
• throw
• The nearest catch up the chain
• No catch anywhere
Definitions
• Builds an error with a message
• Launches it and stops the function
• Where it lands
• The program crashes

Exercise 11 — Strict Shop

The shop refuses any purchase that breaks its rules, and the checkout reports each refusal without ever crashing.

Step 1: `buy(gold, item)` throws `"Unknown item: name"` if the item isn't in `prices`, and `"Not enough gold for name"` if its price is above the gold. Otherwise it returns the gold left. Step 2: loop over `cart`. For each item, try to buy it and print `"Bought name, gold left: X"`, updating the gold. On failure, print `"Refused: message"` and keep going. Step 3: print `"Final gold: X"`.

Expected output:

Bought Potion, gold left: 70 Refused: Unknown item: Sword Refused: Not enough gold for Elixir Bought Map, gold left: 30 Final gold: 30
Starter code
const prices = { Potion: 30, Elixir: 120, Map: 40 }; const cart = ["Potion", "Sword", "Elixir", "Map"]; let gold = 100; // Write your function here // Run the checkout here
Back to the course