Comments

Handling JavaScript Errors With Try, Catch and Finally

JavaScript Errors

Does debugging through errors drive you crazy sometimes? Working through errors can be time consuming, while debugging an application. It is important to write clean code that accounts for error handling. In this post, we will learn how to use Try, Catch and Finally to handle JavaScript errors.

Types of JavaScript Errors

Errors are actually a good thing. It can indicate to us that something went wrong, and helps us take a corrective action. It can happen due to various reasons at anytime. Here is an exhaustive list of the different types of errors you will see in JavaScript.

Below are some common types of errors that we encounter in our application.

Syntax Errors

This is the most common type of error you will see in any programming language. If you are not familiar with the syntax of that programming language, you will run into these more often. These can be avoided to a great extend with the use of modern IDEs and tools which can help with auto-typing based on the programming language.

An example of a syntax error is shown below:

try {
   myFunction("alert('Hey there)");  
}
catch (e) {
  console.error(e.message);
}
// SyntaxError Invalid or unexpected token

Missing a closing quote in the above example, results in a syntax error. Keep in mind that syntax errors are the easiest to fix with the help of linters and modern IDEs that help you with the syntax.

Reference Errors

This is another common error, that you will encounter while coding in JavaScript. A reference error is thrown when trying to dereference a variable that has not been declared.

function scope() { 
  var a = 1;
  var b = 2;
  return a + b;
}
console.log(a); // ReferenceError a is not defined.

The above code snippet will result in a reference error, because cannot be accessed outside the function scope. 

Type Errors

JavaScript also throws another error that is quite commonly seen known as the TypeError. Type errors are thrown when a value is of incompatible type than expected. Let’s take a look at an example below to demonstrate type errors.

var number = 100;
num.toUpperCase(); /* throws a type error (since toUpperCase() is a string method, a number can't be converted to lowercase) */ 

Try and Catch

In JavaScript, the try statement allows you to add a block of code that will be tested for errors when it is executed. If an error does occur in the try block, the corresponding catch statement will be executed. You can think of the try and catch statements as a pair.

try {
  // Code that is executed within error
}
catch(error) {
  // Block of code that is executed when an error occurs in try
}

Let’s see an example, that will throw an error in the try block and hence fallback to the catch block.

try {
   throw new Error('Throwing an error');
}
catch (e) {
  console.error(e.message);
}

// Output:
// Throwing an error

You can see in the example above, that the catch block is executed, since the try block throws a JavaScript error.

Adding Finally

You can also add another block to the try and catch pair. Finally is an optional piece that will contain a block of code that will always be executed, regardless of whether an error occurred or not. We can extend our previous example, by adding the finally block.

try {
   throw new Error('Throwing an error');
}
catch (e) {
  console.error(e.message);
}
finally {
 console.log('Runs finally');
}
// Output:
// Throwing an error
// Runs finally

Notice in the example above that finally is run at the very end after the try and catch blocks are executed (as the name finally implies).

What is throw?

You may have noticed our code samples use the keyword throw in the try block.  The throw operator is useful to send custom errors. Sometimes, errors maybe meaningless and developers can create their own custom errors using throw. You can add a name and message to the error and create your own custom error using throw. We have used throw in all throw a custom error.

try {
   // custom error
   throw new Error('Throwing a custom readable error');
}
catch (e) {
  console.error(e.message);
}
// Output:
// Throwing a custom readable error

Conclusion

Let’s have a quick recap of the three main concepts we learned today.

  • try – Contains a block of code that will be executed, until it encounters an error.
  • catch – Block of code that will be executed if an error is produced by the corresponding try block.
  • finally – Block of code that will be executed after the try and catch, irrespective of whether an error occurred or not.

If you are looking to learn JavaScript in depth, I highly recommend Mosh’s JavaScript courses. The link to all of the courses are below:

Mosh’s JavaScript Course Bundle

If you enjoyed this post, share and spread the word. You can follow me on twitter at @AdhithiRavi

Adhithi Ravichandran is a Senior Software Engineer based in Kansas City. She is currently working on building mobile apps using React Native for critical healthcare scenarios. Adhithi is a regular conference speaker at various tech conferences. Adhithi graduated with a Masters degree in Computer Science from the University of Kansas and has been in the tech industry for over 7 years. She has worked on several technologies over the years, and one of her recent favorite is React Native.
Tags: , , , , ,

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts