JavaScript
  Home arrow JavaScript arrow Page 2 - Exception Handling in JavaScript: Catching...
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 
Sun Developer Network 
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: Catching User Input
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2005-09-27

    Table of Contents:
  • Exception Handling in JavaScript: Catching User Input
  • Using multiple error handlers: a quick overview of the previous script
  • Catching user data: triggering errors through web forms
  • A quick and dirty error handler: using JavaScript prompts

  • 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: Catching User Input - Using multiple error handlers: a quick overview of the previous script


    (Page 2 of 4 )

    If working with multiple exception handlers is still a pretty foreign concept to you, let’s refresh what you’ve learned until now, by taking a quick look at the script developed in the previous tutorial. As you probably remember, it was a simple link generator, which implemented multiple handlers. The whole example looked like this:

    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(){
        var W3C=document.getElementById&&document.createElement&&document.
    getElementsByTagName;
        if(W3C){
            addLinks();
        }
    }

    As you can see, the above script simply generates some links on the fly by using some DOM methods, and works with several error handlers to manipulate three specific primary error types: reference, range and type errors. Notice how the whole “addLinks()” function includes the familiar “try” block, which as I described before, is helpful for trapping raised errors within the corresponding “catch” block.

    Now, with all the hard work for handling errors placed inside a catch statement, I was able to trigger deliberately some primary error types, by replacing portions of code with erroneous instructions. With reference to this concept, a simple way to trigger a reference error is by replacing the below line:

    var as=document.createElement('a');

    with the following one:

    var a=document.createElement('a');

    After running the script, the JavaScript interpreter complains loudly by throwing a reference error, which is nicely caught by the program, as you can see below:

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

    Or, if this example isn’t illustrative enough, I can go further by triggering a type error, taking out this line:

    var links=new Array
    ('home.htm','profile.htm','products.htm','contact.htm');

    and substituting this one:

    var links=new Array
    (1234,'profile.htm','products.htm','contact.htm');

    True to form, the script happily traps a type error, by outputting the following message:

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

    As you can see, some primary error types are easily handled by the above example, which means that this ability should be taken into account when developing programs that implement a strong interaction through a user interface. So far, I’ve demonstrated how potential errors can be raised by introducing bad code within an existing function, but…is it possible to handle errors introduced either by well-intended or malicious users? Fortunately, the answer is affirmative, even when user input should always be verified through server-side mechanisms.

    With reference to handling errors, which might be triggered by external input, the next step consists of writing a few examples that show roughly how user-triggered errors can be trapped trough the proper exception handlers. Thus, keep reading to find out how this is done.

    More JavaScript Articles
    More By Alejandro Gervasio


       · The third part of the series demonstrates how to deliberately raise errors, in order...
     

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT