AI Hints
Home›JavaScript Tutorial›Getters and Errors
JavaScript · Lesson 75 of 138

Throwing Errors

Your own errors.

⏱ 2 min read▶ Video at 1:30:58🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Throwing Errors
From the video: Throwing Errors
  • 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.

app.jsjavascript
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);
  }
}
Output
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.

keyvalue
throw new Error(msg)stop with a message
Callercatches and decides
Messageswhat, and the values
Fail earlycheck 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
Next up: Modules — import and export