JavaScript
  Home arrow JavaScript arrow Page 5 - Exception Handling in JavaScript: Using Mu...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Exception Handling in JavaScript: Using Multiple Exception Handlers
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 4
    2005-09-20

    Table of Contents:
  • Exception Handling in JavaScript: Using Multiple Exception Handlers
  • Handling multiple errors: stepping back to the first example
  • Working with primary error types: defining error types for the JavaScript 1.5 specification
  • A practical example: trapping multiple error types
  • Using multiple handlers: working with “if-else if” blocks

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

       · This second tutorial is primarily focused on explaining how to use multiple...
     

    JAVASCRIPT ARTICLES

    - Validating Digits and Dates with jQuery`s Va...
    - Validating Ranges, Emails, and URLs with jQu...
    - More Uses for the jQuery Tooltip Plug-in`s b...
    - Building Image-Based Tooltips with the jQuer...
    - Using the jQuery Tooltip Plug-in`s bodyHandl...
    - Using Rangelength, Min and Max with the Vali...
    - Using Minlength and Maxlength with the Valid...
    - Modifying Tooltip Coordinates with the jQuer...
    - Applying a Fade Out Effect with the jQuery T...
    - Tracking Mouse Movements with the jQuery Too...
    - Checking Online Forms with the Validator jQu...
    - Nested JavaScript Functions as Objects
    - The jQuery Tooltip Plug-in
    - Active Client Pages at the Server
    - ACP Tab Web Page







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT