Skip to navigation

Errors and Exceptions

Errors are often used to notify another piece of code that something went wrong when trying to carry out a task and that error may then be passed on to the user.

When errors are created — thrown — they interrupt the code that’s currently being run, unless they are caught.

For example, you can force an error to be thrown by giving JSON.parse invalid data:


// Produces a SyntaxError

You can account for exceptions being thrown using a construct called a try-catch. It looks like this:

try {
    JSON.parse("a"); // Produces a SyntaxError
} catch (error) {
    // Handle the error

If an error is thrown in the try block it doesn’t prevent continued code execution - the error is passed into the catch block for you to deal with. Here, for example, you could tell the user that the JSON that was passed in was invalid.

The error passed to the catch block (like a function) is an object with a message property you can use to see what went wrong.

Creating errors

It’s possible to generate your own errors for someone else to deal with. This is done using the throw keyword:

throw new Error("I hungry. Fridge empty.");

Defensive code

Errors are most common at the front line where data from outside your code is brought in, and so those are the areas you need to be most careful.

Try-catch blocks are one way of handling errors, but you can also check the type of some data and provide sensible defaults if you do receive ill-formatted data. Being defensive in your code is a good way of avoiding errors.