Errors: throw, try, catch, finally

Throw an error when input is bad, catch it further up, and run cleanup code in finally either way.

JavaScript · beginner · 7 min · 13 steps · free

What you'll learn

Errors.js

function parseAge(text) {
  const age = Number(text);
  if (Number.isNaN(age)) {
    throw new Error(`"${text}" is not a number`);
  }
  return age;
}

try {
  console.log(parseAge('36'));
  console.log(parseAge('abc'));
  console.log('never printed');
} catch (err) {
  console.log('Error:', err.message);
} finally {
  console.log('done checking');
}

Step by step

  1. Before the first line runs, JavaScript reads the whole file: the function parseAge already exists. This is called hoisting.
  2. JavaScript calls parseAge(), with text = "36". It gets its own variables.
  3. age is created with the value 36.
  4. Number.isNaN(age) is false, so the if-block is skipped.
  5. parseAge returns 36.
  6. parseAge() has finished, so its variables are gone. It prints 36.
  7. JavaScript calls parseAge(), with text = "abc". It gets its own variables.
  8. age is created with the value NaN.
  9. "abc" is not a number, so the check is true.
  10. throw stops parseAge at once and sends the error up the call stack.
  11. The error lands in the catch block. The rest of the try block is skipped.
  12. It prints Error: "abc" is not a number.
  13. finally runs whether or not there was an error: a good place for cleanup.

Common mistakes

Best practices

Key takeaways

Check yourself

An error with no catch?

Answer: Stops the program

finally runs after a return in try?

Answer: Yes

·

More in Asynchronous JavaScript