Throwing Errors
Your own errors.
Sometimes your own code should refuse to continue. Withdrawing more money than an account has. Setting an age of minus five. Throwing an error stops the bad action, and tells the caller exactly what went wrong.

- Refuse bad actions
- Too much money, negative age
- throw an error
throw new Error
Withdraw checks the amount first. If it's too much, throw new Error stops the function immediately, with a helpful message. The caller catches it, and decides what to do. Here, the first withdrawal works, and the second is refused. Run it.
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error(`Cannot withdraw ${amount}, balance is ${balance}`);
}
return balance - amount;
}
for (const amount of [30, 500]) {
try {
console.log("New balance:", withdraw(100, amount));
} catch (e) {
console.log("Refused.", e.message);
}
}New balance: 70 Refused. Cannot withdraw 500, balance is 100
Good error messages
A good error message says what went wrong, and includes the values involved. Cannot withdraw five hundred, balance is a hundred, is far more useful than just, error. Throw errors early, as soon as you spot bad input. It makes bugs much easier to find.
| key | value |
|---|---|
| throw new Error(msg) | stop with a message |
| Caller | catches and decides |
| Messages | what, and the values |
| Fail early | check inputs first |
Summary
Throw new Error stops a function and explains the problem, so the caller can handle it. Next, splitting code into modules.
Key takeaways- throw new Error(...)
- Helpful messages
- Fail early