Home arrow JavaScript arrow Page 2 - Exception Handling in JavaScript: Catching User Input
JAVASCRIPT

Exception Handling in JavaScript: Catching User Input


In a previous article, Alejandro Gervasio explained some key concepts related to working with primary error types, and how they are raised by JavaScript interpreters. This article will focus on developing specific sample code for trapping most of the primary error types according to data entered by users.

Author Info:
By: Alejandro Gervasio
Rating: 4 stars4 stars4 stars4 stars4 stars / 14
September 27, 2005
TABLE OF CONTENTS:
  1. · Exception Handling in JavaScript: Catching User Input
  2. · Using multiple error handlers: a quick overview of the previous script
  3. · Catching user data: triggering errors through web forms
  4. · A quick and dirty error handler: using JavaScript prompts

print this article
SEARCH DEVARTICLES

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.


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