How do we use try...catch...finally statement in JavaScript?

Front End TechnologyJavascriptWeb Development

Whenever we are writing code we may have unwanted exceptions (errors) like syntax errors, reference errors, or range errors in our code. We can handle those errors by using the try and catch block.

In this tutorial, we will learn the use of try…catch…finally statement in JavaScript. The try-catch and finally statements are used to handle exceptions(error). We will learn how to handle exceptions or errors in JavaScript.

Error handling is used multiple times while operating with data from other authorities or user input.

We have four keywords to handle errors. (i) try (ii) catch (iii) throw (iv) finally.

  • try statement will test a block of code for errors

  • catch statement will handle errors.

  • throw statement lets you create custom errors.

  • finally statement will execute after try and catch.

First of all, we will see the types of errors in JavaScript.

Types of Errors in JavaScript

  • ReferenceError − This type of error occurs when we do not define variables in code.

  • RangeError − This type of error occurs when the number is outside an acceptable range of values

  • SyntaxError − This type of error occurs when we use incorrect syntax in code.

Syntax

At the time of execution of the try block if any error occurs then it will be handled by the catch block.

try {
   //try statements
}
catch (exception) {
   //catch statements
}

Let’s see examples for try-catch.

Example

In this example, we will use the try and catch block only and understand how to reference error is handled by the catch block. We will take two variables one is ‘a’ and the other is ‘b’. First, we will print the sum of ‘a’ and ‘b’. Then we try to find the sum of variables ‘a’ and ‘c’ (where ‘c’ is not defined).

<html>
<head>
   <title>Use of try, catch and finally in JavaScript</title>
</head>
<body>
   <h2>Use of try, catch and finally in JavaScript</h2>
   <h4>Variable is not defined, so an error occurs.</h4>
   <p id="div1"> </p>
   <p id="div2"> </p>
   <script>
      let Div1 = document.getElementById("div1");
      let Div2 = document.getElementById("div2");
      var a = 2;
      var b = 3;
      try {
         Div1.innerHTML = `sum of a and b is: ${a+b}`;
         a + c;
      } catch (error) {
         Div2.innerHTML = error;
      }
   </script>
</body>
</html>

In the above example we can see in the try statement block we define variables ‘a’ and ‘b’ but variable ‘c’ is not defined. So when the summation of a+c is executed, at that time Reference error is occurred and this error is handled by the catch block.

When an error occurs in a try block, the remaining instructions will not execute the try block.

If we do not use the try-catch block in our code, then the whole program gets terminated when an error has occurred.

Using finally block with try-catch

The finally statements will execute after try and catch the block. The finally is not dependent on the try or catch block, hence it will always execute whether the try-catch block executes or not.

Syntax

try {
   //try statements
}
catch (exception) {
   //catch statements
}
finally {
   //finally statements
}

Example

In previous code, we will add finally block to the code and understand how it will execute. Here we will print value of variable ‘a’ and ‘b’ using finally block.

<html>
<head>
   <title> Example - Use of try, catch and finally in JavaScript
</title>
</head>
<body>
   <h2> Use of try, catch and finally in JavaScript </h2>
   <h4> finally block is executed after try and catch block. </h4>
   <p id="div1"> </p>
   <p id="div2"> </p>
   <p id="div3"> </p>
   <p id="div4"> </p>
   <script>
      let Div1 = document.getElementById("div1");
      let Div2 = document.getElementById("div2");
      let Div3 = document.getElementById("div3");
      let Div4 = document.getElementById("div4");
      var a = 2;
      var b = 3;
      try {
         Div1.innerHTML = "sum of a and b is: " + `${a+b}`;
         a + c;
      } catch (error) {
         Div2.innerHTML = error;
      } finally {
         Div3.innerHTML = "value of a is: " + a;
         Div4.innerHTML = "value of b is: " + b;
      }
   </script>
</body>
</html>

In the above example, when we add finally a block in the code, we are getting the value of variables ‘a’ and ‘b’. we can see finally the block is executed after the try and catch block.

Conclusion

We learned how to use try-catch-finally in JavaScript with examples. By using try-catch statements we can handle unwanted errors during the execution of code. If we do not use try-catch, our program stops executing when an error occurs but by use of try-catch we can catch and handle those errors. Finally, the block is used to run instructions after try-catch no matter if there is an error or not.

raja
Updated on 25-Jul-2022 07:22:13

Advertisements