30 Days Of JavaScript

Day 9: errors

Lesson 1: Throw

Sometimes things go wrong and code needs to throw an error.

If something in your code goes wrong you can throw an error like this:

Sadly the playground can't show you anything here but, if you open your browsers developer console you will see a big error message displayed when that code runs. To bring up the console in Chrome you can right click anywhere on the page and select Inspect, in the new area that pops up select Console and you'll see lots of logging and, hopefully at least one error message with Something went wrong in it.

The reason that this error message has landed up in the console like this, even though we never explicitly said to, is that nothing in our playground caught it after being thrown. So the browser caught it and put it in the console for us.

If we wanted to deal with this error ourselves we could do that like this:

Notice how we have called throw inside a try block and then followed it up with a catch block?

Well this is some special syntax that lets us try something, this might cause an error and then catch any errors that get thrown inside that try, handling the error gracefully.

So, now if you look in your developer console in the browser you won't see the error logged out, instead you'll see our nice log in both the playground and the browser console.

Important

It's important to know that any functions that throw an error, will also get caught by your catch block.

Let's look at this code

1const naughtyFunction = (number) => {
2  if (number === 5) {
3    throw new Error("Surprise! 5 causes an error");
4  }
5  return number + 1;
6};

This is a silly function but it highlights an important concept. When using functions that you didn't write you won't know what may cause an error, so if you need to deal with an error when using it, you should wrap it in a try/catch like this:

1try {
2  const nextNumber = naughtyFunction(5);
3  console.log(nextNumber);
4} catch {
5  // handle error
6}

Even though we don't throw an error in the try, one can be thrown from naughtyFunction so we need to wrap the call in a try/catch if we want to handle it gracefully.

Knowing when to use a try/catch isn't always obvious and is something that comes with time spent coding, so don't worry if at this point it's a bit confusing. It certainly was for me when I started out.

What if we want to do more with that error though?

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co