Lesson 10 of 14 · 9 min

Handling errors

Things go wrong: a user types "forty" where you expected a number, a file is missing. JavaScript reports problems with errors.

You can create your own with throw:

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

When an error is thrown, the function stops immediately, and so does everything that called it... unless someone catches the error:

try {
  withdraw(50, 80);
  console.log("This line never runs");
} catch (error) {
  console.log("Problem: " + error.message);  // Problem: Not enough money
}
  • Code in try runs normally until something throws.
  • Then catch runs, with the error object. error.message is the text you gave it.
  • After catch, the program carries on.

Throw when a function cannot do its job properly. Catch where you know how to recover, for example by showing a friendly message.

Number("abc") gives NaN ("not a number"). Check for it with Number.isNaN(value).

Your task

  1. Write parseAge(text). It turns the text into a number and returns it, but throws:
    • new Error("Not a number") if the text is not a number,
    • new Error("Age out of range") if the age is below 0 or above 130.
  2. Write safeParseAge(text), which returns parseAge(text), or null if that throws.
main.js
function parseAge(text) {
  const age = Number(text);
  // throw for bad input, otherwise return age
}

function safeParseAge(text) {
  // use try / catch
}

console.log(safeParseAge("31"));
console.log(safeParseAge("thirty"));

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…