We now have a youtube channel. Subscribe!

The definitive guide to proper Error Handling in JavaScript



Hello guys! I want to welcome you all to this new tutorial on JavaScript. I just rounded up with JavaScript Objects in my previous tutorial. So in this tutorial am going to be discussing about an advanced aspect of JavaScript.

I will be discussing about the various types of errors in JavaScript, and also the ways to handle these errors whenever they occure.

There are three types of errors in programming: (a) Syntax Errors, (B) Runtime Errors, (c) Logical Errors.

Syntax Errors

Syntax errors, also called parsing errors, occur at compile time in any traditional programming language and at interpreter time in JavaScript.

For example, the following line causes a syntax error cuz it is missing a closing parenthesis.

<script  type = "text/javascript">
     <!--
          window.print( ;
     //-->
</script>

When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and the rest of the code in other threads gets executed assuming nothing in them depends on the code containing the error.

You can also read our tutorial post on: The IE 4 DOM in JavaScript with examples

Runtime Errors

Runtime errors, also known as exceptions, occur during execution after compilation of the code for traditional programming language, and the interpretation in JavaScript language.

For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist.

<script  type = "text/javascript">
     <!--
          window.print( );
     //-->
</script>

Exceptions also affect the thread in which they occur, allowing other JavaScript thread to go on with their normal execution.

Logical Errors

Logical errors can be the most difficult type of errors to track down. These errors are not as a result of a syntax or runtime error. Instead, they occur whenever you make a mistake in the logic that drives your script and so you end up not getting the result you expected.

You cannot catch those errors, because it is dependent on your business requirement what type of logic you want to put in your program

You can also read our tutorial post on: The ultimate guide to JavaScript Date object


The try...catch...finally Statement

The latest versions of JavaScript added lots of exception handling capabilities. JavaScript now implements the try...catch...finally construct as well as throw operators to handle exceptions.

You can catch programmer-generated and also runtime errors, but you can not catch JavaScript syntax errors.

Below is the try...catch...finally block syntax -

<script  type = "text/javascript">
     <!--
          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>

The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block in the program executes unconditionally after the try/catch.

Example

Here is an example where we are trying to call a non-existing function which in turn is raising an exception. Let us see how it behaves without the try...catch.

<html>
     <head>
          <script  type = "text/javascript">
               <!--
                    function  myFunc()  {
                         var  a =  100;
                         alert("Value of the Variable is :  "  +  a  );
                    }
               //-->
          </script>
     </head>

     <body>
          <p>Click the following to see the result</p>

          <form>
               <input  type = "button"  value = "Click Me" onclick = "myFunc();"    />           
          </form>
     </body>
</html>

Output

Below is the output of the above example.

Click the following to see the result

You can also read our tutorial post on: Learn how to implement JavaScript Literals with examples

Now let us try to catch this exception using the try-catch and display a user-friendly message. You can also suppress this message, if you want to hide this error from the user. 

<html>
     <head>
          <script  type = "text/javascript">
               <!--
                    function  myFunc()  {
                         var  a =  100;
                         try  {
                              alert("Value of the Variable 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>

Output

Below is the output of the above example.

Click the following to see the result

You can use the finally block which will always execute unconditionally after the try/catch. Here is an example below.

<html>
     <head>
          <script  type = "text/javascript">
               <!--
                    function  myFunc()  {
                         var  a =  100;
                         try  {
                              alert("Value of the Variable is :  "  +  a  );
                         }
                         catch  ( e )  {
                              alert("Error :  "  +  e.description  );
                         }
                         finally  {
                              alert("Finally block will always execute!");
                         }
                    }
               //-->
          </script>
     </head>

     <body>
          <p>Click the following to see the result</p>

          <form>
               <input  type = "button"  value = "Click Me" onclick = "myFunc();"    />             
          </form>
     </body>
</html>

Output

Below is the output of the above example.

Click the following to see the result

You can also read our tutorial post on: What is JavaScript


The throw Statement

You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.

Example

The following example below shows how to use a throw statement.

<html>
     <head>
          <script  type = "text/javascript">
               <!--
                    function  myFunc()  {
                         var  a =  100;
                         var  b =  0;
                         
                         try  {
                              if  ( b == 0 )  {
                                   throw("Divide by zero error.");
                              } else {
                                   var  c =  a / b; 
                              }
                         }
                         catch  ( e )  {
                              alert("Error :  "  +  e  );
                         }
                    }
               //-->
          </script>
     </head>

     <body>
          <p>Click the following to see the result</p>

          <form>
               <input  type = "button"  value = "Click Me" onclick = "myFunc();"    />           
          </form>
     </body>
</html>

Output

Below is the output of the above example.

Click the following to see the result

You can raise an exception in one function using a string, integer, Boolean, or an object and then you can capture that exception either in same function as we did in the above example, or in another function  using a try...catch block.


The onerror() Method
The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object when ever an exception occurs on the page.

<html>
     <head>
          <script  type = "text/javascript">
               <!--
                    window.onerror =  function()  {
                         alert("An error occurred!");
                    }
               //-->
          </script>
     </head>

     <body>
          <p>Click the following to see the result</p>

          <form>
               <input  type = "button"  value = "Click Me" onclick = "myFunc();"    />          
          </form>
     </body>
</html>

Output
Below is the output of the above example.

Click the following to see the result

You can also read our tutorial post on: How to enable JavaScript

The onerror event handler provides three pieces of information to identify the exact nature of the error -

  • Error message - This is the same message that the browser would display for the given error.
  • URL - The file in which the error occurred.
  • Line number - The line number in the given URL that caused the error.

Example
Below is an example to show how to extract this information.

<html>
     <head>
          <script  type = "text/javascript">
               <!--
                    window.onerror =  function (msg,  url,  line )  {
                         alert("Message :  "  +  msg  );
                         alert("url :  "  +  url  );
                         alert("Line number :  "  +  line  );
                    }
               //-->
          </script>
     </head>

     <body>
          <p>Click the following to see the result</p>

          <form>
               <input  type = "button"  value = "Click Me" onclick = "maFunc();"    />          
          </form>
     </body>
</html>

Output
Below is the output of the above example.

Click the following to see the result

You can also display extracted information in what ever way you think is better.

You can use an onerror method as shown below, to display an error message incase there is any problem in loading an image.

<Img   src ="myimage.gif"     onerror ="alert('An error occurred loading the image.')" />       

You can use onerror with many HTML tags to in displaying appropriate messages in case of any errors.

Alright guys! we have come to the end of this tutorial on errors and exception handling. In my tutorial, i will be discussing about the basic form validation in JavaScript.

Ask your questions where necessary using the comment box below and i will attend to your questions in due time. Follow us on our various social media platforms available and subscribe to our newsletter to get our tutorial delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain