Sikau

JavaScript · Day 66 · about 25 min

Errors on purpose

throw, Error and finally.

Saying no, clearly

A function asked to divide by zero, or to withdraw more money than there is, should refuse loudly instead of returning nonsense. You can create errors yourself with throw.

throw and catch

function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Not enough money");
  }
  return balance - amount;
}

try {
  console.log(withdraw(500, 200));
  console.log(withdraw(500, 900));
  console.log("never reached");
} catch (err) {
  console.log("Problem:", err.message);
} finally {
  console.log("Receipt printed");
}

There are built-in error types too: TypeError, RangeError… throw new RangeError("Too big") tells the reader what kind of problem it is.

The rest of this lesson

  • Throw early, catch where you can helpexplain
  • Predict the outputpredict
  • try, catch, finallypredict
  • Error handling wordsmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript