17 - Exception handling in Javascript

To err is human. Programmers are no exception to this fact. When writing a program one should think of all the possible cases of execution. It is natural to miss out some cases due to which the working of the program may fail. If a program interacts with the user and operates based on the input from the user then one cannot predict if the input would be correct and conforms to the format required by the program to operate properly.

For example, let us say, we have three textboxes in our page along with a button. The first text box takes a number and the second text box also takes a number by which the number in the first text box is to be divided. After the button is clicked the result would be calculated and displayed in the third text box. For most cases this would work correctly. What if the user enters 0 in the second textbox? This is called an exception.

Formally, an exception can be explained as a run time error that occurs during the execution of the program. It has to be handled in order for the program to complete execution successfully.

Try..Catch

Exceptions are handled by using the try block and the catch block. As we know, a block is one or more statements that appear inside a pair of braces. A try block is one such block which has the keyword ‘try’ prefixed to it. The statements which are placed inside the block would be subjected to exception handling. Those outside it would not be handled for exceptions. The Catch block is meant to take the corrective action for handling the error.

One thing that should be noted here is that these blocks should not be used for validations. Here is an example.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
           function displayalert()
           {
             try
              {
                var divElement = document.getElementById("side");
                alert(divElement.innerHTML);
                alert("Handled error");
              }
            catch(e)
             {
                alert("The error name is " + e.name + ", and the message is "+ e.message);
             }
           }        
        </script>
    </head>     
    <body style = "font-size:16px;">
        <hr>
        <div id="main" align="center">
          Hello!
          <br/>
          <button onclick="displayalert()">Display Alert</button>
        </div>
        <script type="text/javascript">        
        </script>
    </body>
</html>


Note here that there is no element which has the id ‘side’. Hence the var divElement has the value null. When trying to access the property of null, an exception arises. The alert statement after the statement is not executed. As a rule the statements after the error statement in the try block are skipped.

Take a note of the catch block. It takes an argument ‘e’. e is the error object. There are two parts to it, one the name and the other the message. The name identifies the type of error. The message conveys what the error is. Also, note that one can modify the alert message to display any other message. In fact other statements can be placed inside the catch block.

There are several types of errors. Here are some for reference.

Name of the error

Description about the error

TypeError

This error occurs whenever the type expected in the variable is not present.

ReferenceError

This error occurs whenever a reference is illegal.

RangeError

This error occurs whenever an out of range access occurs.

URIError

This error occurs whenever there is an error during the encoding or decoding of an URI which is typically during the use of the function encodeURI()

EvalError

This error occurs whenever there is an error in the execution of the eval() function.

SyntaxError

This error occurs whenever a syntax error occurs inside the eval() function. Other syntax errors are handled by the web browsers and the error message is displayed by them.

In the above example, modify the catch statement as below.

catch(e if e instanceof RangeError)
            {
                alert("The error name is " + e.name + ", and the message is "+ e.message);
            }


When you click the button, nothing happens. Because the type of error caught is not a RangeError. The above snippet shows that we can write separate catch block for each kind of error. This also implies that when writing like this a try block can have several catch blocks. But it is best to define only one catch block for one particular type of error.

Just a minute! What type of error, if changed to, in the above snippet would get it to work like it did so earlier? (Hint: Look into the name of the error shown in the alert box!)

throw – your own errors

Well, so far, what we have seen is the errors that occur programmatically. An exception arises if there is a null reference or a type mismatch and so on. What if we would like to throw errors on the basis of the functionality?

Let us take an example. Suppose we have a textbox in which we expect numbers only. We will display the number that is entered in the textbox. If a number is not entered then we will throw an error message created by us.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
          function displayalert()
          {
            try
            {
                var textElement = document.getElementById("textbox");
                if(isNaN(parseInt(textElement.value)))
                {
                    throw new Error("The entered value " + textElement.value + " is not a number");
                }
                else
                {
                    alert("The value is " + textElement.value);
                }
            }
            catch(e)
            {
                    alert("The error name is " + e.name + ", and the message is "+ e.message);
            }
          }        
        </script>
    </head>
     
    <body style = "font-size:16px;">
        <hr>
        <div id="main" align="center">
          Hello!
          <br/>
          <input type="text" id="textbox"/>
          <br />
          <button onclick="displayalert()">Display Alert</button>
        </div>
        <script type="text/javascript">        
        </script>
    </body>
</html>


From the outputs one can see that the error is raised by the programmer when the input is not in the expected format.

Finally

Previously it was mentioned that the statements after the erroneous statement in the try block will be skipped and not executed. The finally block comes after the catch block. The statements within this block will be executed after the statements in the try. Even if an exception occurs, the statements are executed after executing the statements in the catch block.

Let us add a finally block to our previous example and see the outcome, shall we?

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
          function displayalert()
          {
            try
            {
                var textElement = document.getElementById("textbox");
                if(isNaN(parseInt(textElement.value)))
                {
                    throw new Error("The entered value " + textElement.value + " is not a number");
                }
                else
                {
                    alert("The value is " + textElement.value);
                }
            }
            catch(e)
            {
                alert("The error name is " + e.name + ", and the message is "+ e.message);
            }
            finally
            {
                alert("Inside finally");
            }
          }        
        </script>
    </head>
    <body style = "font-size:16px;">
        <hr>
        <div id="main" align="center">
          Hello!
          <br/>
          <input type="text" id="textbox"/>
          <br />
          <button onclick="displayalert()">Display Alert</button>
        </div>
        <script type="text/javascript">        
        </script>
    </body>
</html>


The following is the output when there is no error raised.

The following is the output when there is an error raised.

Like us on Facebook