Home arrow JavaScript arrow Page 5 - Exception Handling in JavaScript: Using Multiple Exception Handlers
JAVASCRIPT

Exception Handling in JavaScript: Using Multiple Exception Handlers


In this article, you will learn how to work with multiple exception handlers in JavaScript, and deal with primary error types. This will be illustrated by several examples, to get you familiar with JavaScript exceptions.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 9
September 20, 2005
TABLE OF CONTENTS:
  1. · Exception Handling in JavaScript: Using Multiple Exception Handlers
  2. · Handling multiple errors: stepping back to the first example
  3. · Working with primary error types: defining error types for the JavaScript 1.5 specification
  4. · A practical example: trapping multiple error types
  5. · Using multiple handlers: working with “if-else if” blocks

print this article
SEARCH DEVARTICLES

Exception Handling in JavaScript: Using Multiple Exception Handlers - Using multiple handlers: working with “if-else if” blocks
(Page 5 of 5 )

As I said before, the next thing to be done is rewrite the same function by using multiple exception handlers. Thus, the rewritten function is as follows:

function addLinks(){
    // define links
    try {
        var links=new Array
('home.htm','profile.htm','products.htm','contact.htm');
        for(var i=0;i<links.length;i++){
            // create <a> elements
            var as=document.createElement('a');
            // add href property
            as.href=links[i];
            // add title property
            as.title=links[i].replace(/.htm/,'');
            // add link labels
            as.appendChild(document.createTextNode(' '+as.title+'
'));           
           // add links to document tree
            document.body.appendChild(as);
        }
    }
    catch(e){
        // check if error is TypeError
        if(e instanceof TypeError){
            var message='Variable type is not correct!';
        }
        // check if error is ReferenceError
        else if(e instanceof ReferenceError){
            var message='Incorrect reference!';
        }
        // check if error is RangeError
        else if(e instanceof RangeError){
            var message='Value is out of range!';
        }
        // error is unknown
        else{
            var message='Unknown error!';
        }
        var p=document.createElement('p');
        p.appendChild(document.createTextNode('The following
exception was thrown by the script :'+message+' Error
name :'+e.name+' Error message :'+e.message));
        document.body.appendChild(p);
    }
}
// call function when page is loaded
window.onload=function(){       
    varW3C=document.getElementById&&document.
createElement&&document.getElementsByTagName;
    if(W3C){
        addLinks();
    }
}

As you can see, the above script remains mostly the same. Of course the only change worth noting is within the “catch” block. As listed above, the script implements a different exception handler for three of the primary error types, since it is capable of trapping each error and displaying a custom message in all of the cases.

Now the code is more robust and simpler to read, since it’s capable of discerning between different error types, which makes it correct from a programming point of view.

Again, by purposely changing the pertinent code, it’s possible to raise errors that will be caught by the corresponding handler. To exemplify this condition, if I replace the “var links” definition with a “var lnk” expression, the script traps a reference error:

The following exception was thrown by the script :Incorrect
reference! Error name :ReferenceError Error message :links is not
defined

Similarly, a type error can be caught by replacing the line:

as.title=links[i].replace(/.htm/,'');

with this one:

as.title=links[i].replae(/.htm/,'');

According to this condition, the script’s output is the following:

The following exception was thrown by the script :Variable type
is not correct! Error name :TypeError Error message :links
[i].replae is not a function

As you can see, in this case the corresponding handler has trapped the raised error.

The final example demonstrates a range error, by assigning a large numeric value to the “links” array:

var links=new Array(999999999999999999999999999999999999999999);

As you might guess, the response of the script is as follows:

The following exception was thrown by the script :Value is out of
range! Error name :RangeError Error message :invalid array length

Of course, there is plenty of room to keep on modifying the code and watching raised errors. So, it’s really worthwhile to see how the script behaves in each case. However, one final thing must be noted: if you try to introduce some changes within the code to force a syntax error, generally this error won’t be caught, because the JavaScript interpreter will anticipate this condition when parsing code at runtime and stop program execution.

Most of the syntax errors can be deliberately raised through a user input control, such as (X)HTML forms or a prompt() command, so this exercise will be left for the next part of the series.

Summary

Over this second tutorial, you’ve hopefully learned how to work with multiple exception handlers, as well as dealing with primary error types. In order to satisfy those requirements, several examples were illustrated, as part of the learning process to get you familiarized with JavaScript exceptions.

In the next part of the series, I’ll set up some additional examples for trapping all of the primary error types, along with complementary techniques to make JavaScript code even more compact and readable when using exceptions. You won’t want to miss it! 


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials