Handling Errors with try...catch

Summer School, page 7 of 11. A two-minute read.

Some errors are bugs that you need to fix. But some errors are things you can predict might go wrong, even in perfect code. A user might type something silly. A file might be missing. The internet connection might drop.

For these situations, JavaScript lets you catch errors, so your program can handle them gracefully instead of crashing. It looks like this:

JavaScript
const userInput = "{ this is not valid JSON }";

try {
  const data = JSON.parse(userInput);
  console.log("Got the data:", data);
} catch (error) {
  console.log("😬 Oops! That wasn't valid JSON.");
  console.log("Error type:", error.name);
}

console.log("The program keeps running!");

It prints

😬 Oops! That wasn't valid JSON.
Error type: SyntaxError
The program keeps running!

Here's how it works:

  • JavaScript tries to run the code inside the try block.
  • If everything goes well, the catch block is skipped completely.
  • If an error happens anywhere inside try, JavaScript immediately jumps to the catch block. The error variable holds information about what went wrong, including its name (the type) and its message.
  • Either way, the program carries on after the try...catch, instead of crashing.
Think of it like thisThe trapeze net

A try...catch is like the safety net under a trapeze artist. The performer tries the trick. If they fall, the net catches them, and the show goes on. Without the net... well, the show definitely doesn't go on.

finally

You can add a finally block, which runs no matter what, whether there was an error or not. It's useful for cleaning up, like hiding a "Loading..." message:

JavaScript
function loadSettings(text) {
  console.log("⏳ Loading...");
  try {
    const settings = JSON.parse(text);
    console.log("✅ Loaded theme:", settings.theme);
  } catch (error) {
    console.log("❌ Couldn't load settings. Using defaults.");
  } finally {
    console.log("🏁 Done loading.");
  }
}

loadSettings('{"theme": "dark"}');
loadSettings("garbage!!!");

It prints

⏳ Loading...
✅ Loaded theme: dark
🏁 Done loading.
⏳ Loading...
❌ Couldn't load settings. Using defaults.
🏁 Done loading.
Watch outDon't hide your bugs

It's tempting to wrap everything in try...catch so errors never show up. Don't! Especially, never write an empty catch block like catch (error) { }. That silently swallows the error, so the program carries on in a broken state and you have no idea why. That's not fixing a bug, that's hiding it under the carpet. Only catch errors that you expect and know how to handle.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning