JavaScript Exception Handling

As you know that an exception is an error that occurs at the time of execution due to an illegal operation when the program is syntactically correct.

Ways to Handle Exception in JavaScript

You can handle exception in JavaScript in the following two ways:

Exception Handling using try-catch

Here is an example demonstrates how to handle exception using try-catch statement in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
   <title>JavaScript Exception Handling</title>
   <script type="text/javascript">
      try
      {
         document.write(val);
         document.write("Hello World!, This is Exception Handling.");
      }
      catch(err)
      {
         document.write(err.message);
      }
   </script>
</head>
<body>

</body>
</html>

As you can see from the above example of exception handling in JavaScript, variable val is not defined, therefore here is the output you will watch into your browser after performing the above example of exception handling:

javascript exception handling

Here is another example of exception handling in JavaScript. This example of exception handling, uses another block called finally block that is associated with the try-catch statement. The finally block of the try-catch statement always runs its code whether or not an exception is thrown. Here is the modified version of the above example of exception handling in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
   <title>JavaScript Exception Handling</title>
   <script type="text/javascript">
      try
      {
         document.write(val);
      }
      catch(err)
      {
         document.write(err.message);
      }
      finally
      {
         document.write("<br/>");
         document.write("Hello World!, This is Exception Handling.");
      }
   </script>
</head>
<body>

</body>
</html>

Here is the sample output produced by the above JavaScript exception handling example:

javascript exception handling example

JavaScript Exception Handling using onerror Event

Here is an example of exception handling using onerror event in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
   <title>JavaScript Exception Handling</title>
   <script type="text/javascript">
      window.onerror = function(ermessage, url, line)
      {
         document.write(ermessage+"<br/>");
         document.write(url+"<br/>");
         document.write(line+"<br/>");
      }
      document.write(val);
   </script>
</head>
<body>

</body>
</html>

Here is the sample output produced by the above JavaScript exception handling using onerror event example code:

javascript exception handling using onerror event

JavaScript Online Test


« Previous Tutorial Next Tutorial »