Codiqo

Learn JavaScript · lesson 38 of 60 · about 9 minutes

try...catch and throw

Check a guestbook message: handle errors without crashing, run clean-up code with finally, and signal your own problems with throw.

What you'll learn

  • Wrap risky code in try...catch
  • Use finally
  • Throw your own errors

A message box

Visitors can now leave Sam a message. checkMessage(text) trims it and refuses two kinds of message by throwing an Error: an empty one (Write something first) and one over 140 characters (Too long: 152 characters (max 140)). The page calls it inside try, so a good message is shown with a thank-you, and when checkMessage throws, catch shows Couldn't send: and the error's message instead of the page stopping.

Catching errors

Code in try { } runs normally. If it throws, JavaScript jumps straight to catch (err) { }. finally { } runs afterwards whether or not there was an error.

JSON.parse is a classic thing to wrap: bad text throws a SyntaxError.

Safe JSON parsing

function load(text) {
  try {
    return JSON.parse(text);
  } catch (err) {
    console.log("Bad save file:", err.name);
    return {};
  } finally {
    console.log("Load attempted");
  }
}
console.log(load('{"xp":10}').xp);
console.log(load("oops"));

Output

Load attempted
10
Bad save file: SyntaxError
Load attempted
{}

Throwing your own

throw new Error("message") signals a problem from your own code. The caller can catch it like any built-in error.

throw

function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Insufficient funds");
  }
  return balance - amount;
}
try {
  console.log(withdraw(50, 20));
  console.log(withdraw(50, 80));
} catch (err) {
  console.log("Error:", err.message);
}

Output

30
Error: Insufficient funds

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.