Lesson 9 of 199:28 video

JavaScript error handling

How to read a JavaScript error (its name, its message and the stack trace), how to throw one of your own, how try, catch and finally keep one error from stopping the whole program, and how strict mode turns silent mistakes, like a misspelled variable, into errors.

In this lesson

  1. 0:00 Intro
  2. 1:00 Reading an error
  3. 3:25 Throwing an error
  4. 5:05 try, catch and finally
  5. 6:56 Back to the typo
  6. 7:38 Strict mode
  7. 8:46 Next time

This program keeps a rocket’s fuel level, and one function burns some of it:

let fuel = 80;

function burn(percent) {
  feul = fuel - percent;
}

burn(20);
console.log(fuel); // 80

It prints 80, not 60. There’s no error and no warning. The function ran, and so did the subtraction. Look at the name left of the equals sign: two of its letters are swapped. JavaScript didn’t stop, and it didn’t say a word.

That’s only true under JavaScript’s original rules, which a plain <script> tag and the browser console still use. Paste it into a module and it stops with an error straight away. By the end of this lesson you’ll know why, and you’ll know where the 60 went. First, the error that does show up.

Reading an error

An error can look like JavaScript breaking down. It’s closer to the opposite: JavaScript reached a line it couldn’t carry out, so it stopped and wrote down what went wrong and where. Here’s a small program that stops:

const probe = { name: "Probe", fuel: 0 };

function crewSize(ship) {
  return ship.crew.length;
}

function report(ship) {
  return `${ship.name}: crew of ${crewSize(ship)}`;
}

console.log(report(probe));

Run it as mission.js and the console shows this:

TypeError: Cannot read properties of undefined (reading 'length')
    at crewSize (mission.js:4:20)
    at report (mission.js:8:35)
    at mission.js:11:13

It has three parts:

  • The name, TypeError, is the kind of error.
  • The message says what happened. The probe has no crew, so ship.crew was undefined, and the code asked for its length.
  • The stack trace is the lines underneath, each starting with at, and they say where.

The top line of the trace is where the error happened: inside crewSize, in mission.js, line 4, column 20, which is where length is read. The next line is whoever called crewSize, which is report. The last one is whoever called report, the top level of the file. This is the call stack, the pile of calls waiting on each other, written down at the moment something went wrong.

Read the top line first. If it isn’t your code, keep going down until you reach a line that is:

function fuelBar(ship) {
  return "=".repeat(ship.fuel / 10);
}

console.log(fuelBar({ name: "Probe", fuel: -40 }));
// RangeError: Invalid count value: -4
//     at String.repeat (<anonymous>)
//     at fuelBar (mission.js:2:14)

The top line is inside repeat, which is built into JavaScript. The line under it is yours, and that’s where to look.

Chrome and Node print traces this way. Firefox and Safari lay them out differently, but the same three parts are there.

Four kinds of error

Error names come from a short list, and four of them cover most of what you’ll meet:

const crew = ["Ada", "Lee";      // SyntaxError: Unexpected token ';'
console.log(kestral.fuel);       // ReferenceError: kestral is not defined
kestrel.launch();                // TypeError: kestrel.launch is not a function
crew.length = -1;                // RangeError: Invalid array length

Each line gives its error on its own, so try them one at a time.

  • SyntaxError: the code can’t be read at all, like a bracket that’s never closed. Nothing in the file runs, not even the lines above the mistake.
  • ReferenceError: a name that doesn’t exist, often a misspelled one.
  • TypeError: a value that’s the wrong kind for the job, like reading a property of undefined, or calling something that isn’t a function.
  • RangeError: a number outside the range that’s allowed, like an array length of minus one.

Each of these is a class, and they all extend one class, Error. So an error is an object with a name, a message and a stack:

try {
  undefined.length;
} catch (error) {
  console.log(error instanceof TypeError); // true
  console.log(error instanceof Error);     // true
  console.log(error.name);                 // TypeError
  console.log(error.message);              // Cannot read properties of undefined (reading 'length')
}

The try and catch here hold the error so we can look at it. They’re coming up below.

Throwing an error of your own

JavaScript throws those errors when its own rules are broken. Your program has rules too, and JavaScript has never heard of them. Here are three rockets, and one rule: a launch needs 50% fuel.

const kestrel = { name: "Kestrel", fuel: 80 };
const heron = { name: "Heron", fuel: 40 };
const osprey = { name: "Osprey", fuel: 95 };
const fleet = [kestrel, heron, osprey];

function launch(ship) {
  console.log(`${ship.name} lifts off`);
}

launch(heron); // Heron lifts off

Heron lifts off with 40%. Nothing in the language says that isn’t enough. The rule is yours, so the error has to be yours too. Before the print, check the fuel, and if it’s under 50, throw an error:

function launch(ship) {
  if (ship.fuel < 50) {
    throw new RangeError(`${ship.name} needs 50% fuel, has ${ship.fuel}%`);
  }
  console.log(`${ship.name} lifts off`);
}

launch(heron);
// RangeError: Heron needs 50% fuel, has 40%
//     at launch (mission.js:8:11)

throw takes any value and raises it as an error. Make that value an Error object, because it records its stack trace the moment it’s created. throw "low fuel" works too, but it arrives as a plain string with no name and no stack trace. When none of the built-in kinds fits, new Error("...") is the plain one.

What an uncaught error ends

What does a throw do to the code around it? Here’s a function that launches every rocket in the fleet:

function launchAll(ships) {
  for (const ship of ships) {
    launch(ship);
  }
}

launchAll(fleet);
// Kestrel lifts off
// Uncaught RangeError: Heron needs 50% fuel, has 40%
//     at launch (mission.js:8:11)
//     at launchAll (mission.js:15:5)
//     at mission.js:19:1

Kestrel lifts off. Then Heron: launch reaches the throw and stops on that line. It doesn’t return. The error goes back to launchAll, which was waiting for launch to finish, and ends that too, partway through its loop. Then it ends whatever called launchAll. When there’s nothing left to end, the program is over, and the console prints the error with one more word in front: Uncaught.

Osprey, with the fullest tank of the three, never got its turn. One rocket was short on fuel, and that stopped the whole fleet. In a browser the page stays open, and only this run of the script ends. Node stops the whole process.

try, catch and finally

To stop an error on its way, you catch it. Wrap the risky code in a try block and follow it with a catch block. If the try block runs to the end, the catch block never runs. If anything in it throws, even a function several calls deep, the rest of the try block is skipped and the catch block takes over. The error object arrives in the variable in its parentheses, so you can read its message.

Put that inside the loop, around each launch:

function launchAll(ships) {
  for (const ship of ships) {
    try {
      launch(ship);
    } catch (error) {
      console.log(`Grounded: ${error.message}`);
    }
  }
}

launchAll(fleet);
// Kestrel lifts off
// Grounded: Heron needs 50% fuel, has 40%
// Osprey lifts off

Heron throws, the catch block prints why it’s grounded, and the loop carries on to Osprey. The catch block sits inside the loop because the loop knows what to do next: skip that rocket and move on. Catch an error where something can be done about it.

A third block, finally, runs either way, error or no error. It’s for cleanup, like clearing the pad for the next rocket:

function launchAll(ships) {
  for (const ship of ships) {
    try {
      launch(ship);
    } catch (error) {
      console.log(`Grounded: ${error.message}`);
    } finally {
      console.log("Pad clear");
    }
  }
}

launchAll(fleet);
// Kestrel lifts off
// Pad clear
// Grounded: Heron needs 50% fuel, has 40%
// Pad clear
// Osprey lifts off
// Pad clear

try only covers code that runs while it’s open. A callback that runs later, from a setTimeout, is outside it. That’s for the lesson on asynchronous JavaScript.

Catching only what you expect

A catch block takes every error thrown inside its try block, not only the one you were expecting. Say the call inside the try block is written wrong, as if launch were a method of each rocket:

function launchAll(ships) {
  for (const ship of ships) {
    try {
      ship.launch();
    } catch (error) {
      console.log(`Grounded: ${error.message}`);
    }
  }
}

launchAll(fleet);
// Grounded: ship.launch is not a function
// Grounded: ship.launch is not a function
// Grounded: ship.launch is not a function

Three rockets down, and two of them have plenty of fuel. The reason it printed, ship.launch is not a function, is a TypeError: a bug in the code. The catch block handled it like a fuel problem.

So check what you caught. If the error is an instance of RangeError, handle it. If it’s anything else, throw it again, and it carries on as if it had never been caught:

function launchAll(ships) {
  for (const ship of ships) {
    try {
      ship.launch();
    } catch (error) {
      if (error instanceof RangeError) {
        console.log(`Grounded: ${error.message}`);
      } else {
        throw error;
      }
    } finally {
      console.log("Pad clear");
    }
  }
}

launchAll(fleet);
// Pad clear
// Uncaught TypeError: ship.launch is not a function
//     at launchAll (mission.js:16:12)

Now the bug stops the program with a TypeError and a line number. For a bug, that’s what you want. finally still ran: the pad is clear even though the error wasn’t handled there.

To tell your own errors apart from everything else, you can give them a class of their own, class FuelError extends Error {}, and check error instanceof FuelError.

Where the 60 went

Back to the program we started with. A name that doesn’t exist was a ReferenceError earlier, so why wasn’t feul one? Because of what the line does with the name. Reading a name that doesn’t exist is an error:

console.log(fule); // ReferenceError: fule is not defined

But feul = fuel - percent doesn’t read feul. It assigns to it. Under JavaScript’s original rules, assigning to a name nobody declared is treated as a request: make a new global variable with that name, and put the value there. In a browser, the 60 is sitting on window, the built-in object that stands for the tab:

burn(20);
console.log(fuel);        // 80
console.log(window.feul); // 60: a global variable nobody declared

The real fuel was never touched. These old rules are nicknamed “sloppy mode”. (In Node, a CommonJS file does the same, and the 60 lands on globalThis.feul.)

Strict mode

That rule was meant to be forgiving, in a language first built for small scripts. In practice, it hides typos. So in 2009, the fifth edition of JavaScript added strict mode, which turns mistakes like this one into errors. It couldn’t just change the rules, because old pages rely on them, so a file has to ask for it with one line at the very top:

"use strict";
let fuel = 80;

function burn(percent) {
  feul = fuel - percent;
}

burn(20);
// Uncaught ReferenceError: feul is not defined
//     at burn (mission.js:5:8)

The string "use strict" only works as the first statement of a file or a function. Lower down, it’s ignored.

Strict mode changes other mistakes too. A method called with nothing left of the dot gets undefined as this instead of window, so the mistake stops the program right where it happens:

"use strict";
const rocket = {
  fuel: 80,
  launch() {
    console.log(`Liftoff with ${this.fuel}% fuel`);
  },
};

const launch = rocket.launch;
launch();
// Old rules:   Liftoff with undefined% fuel
// Strict mode: TypeError: Cannot read properties of undefined (reading 'fuel')

And writing to a frozen object, which does nothing under the old rules, is an error in strict mode:

"use strict";
const ship = Object.freeze({ fuel: 80 });
ship.fuel = 0;
// TypeError: Cannot assign to read only property 'fuel' of object '#<Object>'

A lot of new code is strict without asking. The body of a class always is, and so is a module, the modern way to split a program into files. Plain <script> tags and the browser console still use the old rules.

Summary

  • An error has a name (what kind), a message (what happened) and a stack trace (where). Read the trace from the top, and go down until you reach your own code.
  • SyntaxError, ReferenceError, TypeError and RangeError all extend Error, so every error is an object with name, message and stack.
  • throw new RangeError(...) raises an error for a rule of your own. An error that isn’t caught ends every call that was waiting on it.
  • try and catch stop an error on its way. Put the catch where something can be done about it, and use finally for cleanup that has to happen either way.
  • Check what you caught with instanceof, and throw anything you didn’t expect again.
  • Under the old rules, assigning to an undeclared name makes a global variable. "use strict" turns that into an error, and modules and classes are always strict.
Video transcript

Intro

This program keeps a rocket's fuel level: eighty. One function, burn, takes some of it away. Burn twenty, then print the fuel. Eighty. Not sixty. No error, no warning. The function ran, and so did the subtraction. Now look at the name left of the equals sign. Two of its letters are swapped. JavaScript didn't stop, and it didn't say a word. So where did the sixty go? Today, we find out.

By the end of this video, you'll understand three things. One: how to read an error: its name, its message, and the stack trace under it. Two: how to throw an error of your own, and how try and catch keep one error from stopping the whole program. Three: why that misspelled name got no error at all, and the one line that would have caught it.

Reading an error

Last time, we ended on an error: a probe with no crew, and a read that stopped the program. So far in this series, a red error message has been where an example ends. Today it's the subject. An error can look like JavaScript breaking down. It's closer to the opposite. JavaScript reached a line it couldn't carry out, so it stopped, and wrote down what went wrong and where. Compare that with the program we opened on, which was wrong and said nothing. So first we'll read an error. Then throw one, then catch one. Then back to that misspelled name.

Here's the probe's error again, inside a small program. One function, crewSize, reads a ship's crew and returns its length. A second, report, calls it. The last line prints a report for the probe. Run it, and the console shows this. It has three parts. The name, TypeError, is the kind of error. The message says what happened: cannot read properties of undefined, reading length. Something was undefined, and the code asked for its length. The lines underneath, each starting with at, are the stack trace, and they say where. The top one is where the error happened: inside crewSize, then the file, the line and the column. The next is who called crewSize: report. The last is who called report. It's the call stack from the functions episode, the pile of calls waiting on each other, printed at the moment something went wrong. Read the top line first. If that isn't your code, keep going down until you reach a line that is.

That name comes from a short list, and four of them cover most of what you'll meet. SyntaxError: the code can't be read at all, like a bracket that's never closed. Nothing in the file runs, not even the lines above the mistake. ReferenceError: a name that doesn't exist, often a misspelled one. TypeError: a value that's the wrong kind for the job, like reading a property of undefined, or calling something that isn't a function. RangeError: a number outside the range that's allowed, like an array length of minus one. Each of these is a class, and they all extend one class, called Error. So an error is an object, with a name, a message and a stack.

Throwing an error

JavaScript throws those when its own rules are broken. Your program has rules too, and JavaScript has never heard of them. Take three rockets in an array: Kestrel with eighty percent fuel, Heron with forty, Osprey with ninety-five. The rule: a launch needs fifty. Call launch with Heron, and it prints Heron lifts off. Nothing in the language says forty isn't enough. The rule is yours, so the error has to be yours too. Before the print, check the fuel. If it's under fifty: throw, then new RangeError, with a message naming the ship and its fuel. throw takes any value and raises it as an error. Make that value an Error object: it records its stack trace the moment it's created. Now launching Heron stops with your message, in the same shape as JavaScript's own: a name, a message, a trace.

What does a throw do to the code around it? Follow this one. A function called launchAll loops over the rockets and calls launch for each. Kestrel lifts off. Then Heron: launch reaches the throw and stops on that line. It doesn't return. The error goes back to launchAll, which was waiting for launch to finish, and ends that too, partway through its loop. Then it ends whatever called launchAll. When there's nothing left to end, the program is over, and the console prints the error with one more word in front: Uncaught. Osprey, with the fullest tank of the three, never got its turn. One rocket was short on fuel, and that stopped the whole fleet.

try, catch and finally

To stop an error on its way, you catch it. Wrap the risky call in a block marked try, and follow it with a block marked catch. If the try block runs to the end, the catch block never runs. If anything in it throws, even a function several calls deep, the rest of the try block is skipped, and the catch block takes over. The error object arrives in the variable in its parentheses, so you can read its message. Put that inside the loop, around each launch. Kestrel lifts off. Heron throws, the catch block prints why it's grounded, and the loop carries on. Osprey lifts off. The catch block sits in the loop because the loop knows what to do next: skip that rocket and move on. A third block, finally, runs either way, error or no error. It's for cleanup. Here, it clears the pad for the next rocket.

A catch block takes every error thrown inside its try block, not only the one you were expecting. Say the call inside the try block is written wrong: ship dot launch, as if launch were a method. Run it. Kestrel, grounded. Heron, grounded. Osprey, grounded. Three rockets down, and two of them have plenty of fuel. Read the reason it printed: ship dot launch is not a function. That's a TypeError, a bug in the code. The catch block handled it like a fuel problem: it printed a line and carried on. So check what you caught. If the error is an instance of RangeError, the same check we used on classes, handle it. If it's anything else, throw it again, and it carries on as if it had never been caught. Now the bug stops the program with a TypeError and a line number. For a bug, that's what you want.

Back to the typo

Which brings us back to the misspelled name we started with. Earlier, a name that doesn't exist was a ReferenceError. So why wasn't this one? Because of what the line does with the name. Reading a name that doesn't exist is an error. That line doesn't read it. It assigns to it. And under JavaScript's original rules, assigning to a name nobody declared is treated as a request: make a new global variable with that name, and put the value there. That's where the sixty went. In a browser, it's sitting on window, the built-in object that stands for the tab, under a name nobody chose. The real fuel was never touched.

Strict mode

That rule was meant to be forgiving, in a language first built for small scripts. In practice, it hides typos. So in 2009, JavaScript added strict mode, which turns mistakes like this one into errors. It couldn't just change the rules, because old pages rely on them. So a file has to ask for strict mode, with one line at the very top: the string use strict. Run the burn again. ReferenceError, with the function and the line number. Strict mode also settles the note we left in the episode on this. Call a method with nothing left of the dot, and old-style code quietly uses window as this. Strict mode leaves this undefined, so the mistake stops the program right where it happens. And a lot of new code is strict without asking. The body of a class always is. So is a module, the modern way to split a program into files.

Next time

That's error handling in one line: an error is an object with a name, a message and a stack trace; you can throw your own when your rules are broken, catch the ones you know how to handle, and let the rest stop the program. And strict mode turns silent mistakes into errors. Next time, we look at code that doesn't run right away: why a timer set to zero milliseconds still runs last, and how promises and async functions keep that kind of code readable.

Learn more