How does Exceptions Handling work in JavaScript?


JavaScript uses try…catch…finally to handle exceptions. The latest versions of JavaScript added exception-handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

Syntax

Here is the try...catch...finally block syntax −

<script>
   <!--
      try {
         // Code to run
         [break;]
      }
      catch ( e ) {
         // Code to run if an exception occurs
         [break;]
      }
      [ finally {
         // Code that is always executed regardless of
         // an exception occurring
      }]
   //-->
</script>

Example

You can try to run the following code to learn how exceptions are handled in JavaScript −

<html>
   <head>
      <script>
         <!--
            function myFunc()
            {
               var x = 20;
               try {
                  alert("Value of variable a is : " + a );
               }
               catch ( e ) {
                  alert("Error: " + e.description );
               }
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following to see the result:</p>
      <form>
          <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>
   </body>
</html>

Updated on: 22-Jun-2020

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements