Learn/JavaScript/9. Handling errors
Lesson 9 of 15
Sign in

JavaScript, lesson 9

Handling errors

Things go wrong: a user types abc where a number belongs, a JSON message is cut off, a withdrawal is larger than the balance. JavaScript reports problems with exceptions. When an exception is thrown, normal execution stops and JavaScript looks for the nearest code that catches it. If nothing does, the program ends with an error message on stderr.

Throwing

You can throw an exception yourself with throw. Almost always, throw an Error object:

An Error carries a message and a stack (where it was created). JavaScript has several built-in subtypes you can use to say what kind of problem happened:

2 exercises to try what you just read.

Exercise 1

JSON inspector

Press Ctrl Enter or Check to test your code.

Exercise 2

Ticket machine

Press Ctrl Enter or Check to test your code.

  • TypeError: a value has the wrong type, such as calling something that is not a function.
  • RangeError: a number is outside the allowed range.
  • SyntaxError: code or data could not be parsed, for example by JSON.parse.
  • ReferenceError: a variable name does not exist.

Catching with try...catch

The try block runs first. If anything inside it throws, even deep inside a function it calls, control jumps straight to catch, and the error object is available as err. If nothing throws, catch is skipped. If you do not need the error object, you may write just catch { ... }.

finally

A finally block runs whether the try block succeeded, threw, or returned early. It is the place for cleanup that must always happen:

Catch only what you expect

A catch block catches everything, including your own typos. So check what you caught, handle the errors you understand, and throw the rest again:

instanceof checks which kind of error it is. You can define your own error types by extending Error. Classes are the topic of the next lesson, but the pattern is short:

When you rethrow with more context, pass the original as the cause so nothing is lost: throw new Error("could not load order", { cause: err }).

Not every problem is an exception

Some operations do not throw at all. Number("abc") quietly returns NaN, and reading a missing array index returns undefined. Check for those yourself with Number.isNaN(x) or Number.isFinite(x), and throw if your function cannot continue. Validating input early and throwing a clear error is much kinder than letting a NaN travel through your program and turn up as a strange result later.

Further reading

  • MDN: Control flow and error handling
  • MDN: try...catch
  • MDN: Error
  • Node.js docs: Errors

Each input line should contain a JSON value. For each line print one result:

  • if JSON.parse succeeds and the value is an array: array of N, where N is its length;
  • if it succeeds with anything else: ok TYPE, where TYPE is the result of typeof (so null prints ok object);
  • if parsing throws: invalid line K, where K is the line number starting at 1.

Sample input:

Sample output:

A ticket machine sells tickets that cost 4 coins each. Write a function buy(count, paid) that returns the change, and throws when something is wrong:

  • a TypeError with message not a number if count or paid is NaN;
  • a RangeError with message count must be 1 to 10 if count is less than 1 or more than 10;
  • a plain Error with message need X more coins if paid is less than the price, where X is the amount missing.

Each input line has two values, COUNT PAID. For each line, call buy inside try...catch and print change N on success, or ERRORNAME: MESSAGE when it throws (use the error's name and message properties).

Sample input:

Sample output:

function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error(`cannot withdraw ${amount}, balance is ${balance}`);
  }
  return balance - amount;
}
try {
  const data = JSON.parse('{"name": "Ada"');   // missing closing brace
  console.log(data.name);
} catch (err) {
  console.log(`Could not read data: ${err.name}`);  // SyntaxError
}
console.log("The program keeps going");
function process(order) {
  console.log("start", order);
  try {
    if (!order) throw new Error("empty order");
    return "done";
  } finally {
    console.log("cleanup", order);   // runs in both cases
  }
}
try {
  riskyStep();
} catch (err) {
  if (err instanceof RangeError) {
    console.log("Value out of range, using default");
  } else {
    throw err;   // not ours to handle
  }
}
class OutOfStockError extends Error {
  constructor(item) {
    super(`${item} is out of stock`);
    this.name = "OutOfStockError";
  }
}
[1, 2, 3]
{"x": 1
"hello"
array of 3
invalid line 2
ok string
2 10
0 5
3 9
x 5
change 2
RangeError: count must be 1 to 10
Error: need 3 more coins
TypeError: not a number