JavaScript basics error handling

JavaScript basics error handling

Chris Bongers
·Aug 30, 2021·

2 min read

Listen to this article

When it comes to writing code that is not breaking, we have to address error handling.

In JavaScript, this is managed through exceptions. But before we dive into those, let's look and see what happens when we introduce some faulty code.

iDontExist();

console.log('log me');

This will result in an error stating:

Uncaught ReferenceError: iDontExist is not defined

And stop our code completely.

Which is not ideal, because we don't want our code to crash right away.

Catching error in JavaScript

The way to catch errors in JavaScript is to wrap them in a try...catch statement.

Let's do just that for the code we have above and see what happens.

try {
  iDontExist();
} catch (error) {
  console.error(error);
}

console.log('log me');

Now this will result in our error being logged, as well as our custom console.log being called.

JavaScript finally statement

To create a complete try...catch statement, we can introduce the finally block.

This block will be called once the whole code block is evaluated, and it doesn't care if it was an error or not.

try {
  iDontExist();
} catch (error) {
  console.error(error);
} finally {
  console.log('fully done');
}

Throwing new exceptions in JavaScript

By now, we have seen how to catch errors, and often these are just the errors JavaScript throws for us.

But we can also introduce our own errors, because there might be some user error.

We can invoke these by using the throw method. This can then use an Error or a custom message.

try {
  throw new Error('my error');
} catch (error) {
  console.error(error);
} finally {
  console.log('fully done');
}

Which will result in a custom error message saying my error.

Nesting try...catch blocks

Another cool thing to note is that we can even nest try...catch blocks. The main thing to note when doing this is that the outer catch block will catch the exceptions.

try {
  try {
    throw new Error('my error');
  } finally {
    console.log('inner done');
  }
} catch (error) {
  console.error(error);
} finally {
  console.log('fully done');
}

console.log('log me');

Resulting in the following flow:

// inner done
// Error: my error
// fully done
// log me

I hope you got a good understanding of error handling in JavaScript. If you have any question, don't hesitate to contact me.

You can also have a play with this on the following CodePen demo.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Did you find this article valuable?

Support Chris Bongers by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this