Learn how to use Try, Catch and Finally to handle 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 _a _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.

#javascript #web-development

Learn how to use Try, Catch and Finally to handle JavaScript errors
1 Likes14.15 GEEK