JavaScript
  Home arrow JavaScript arrow Page 3 - 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 - Catching user data: triggering errors through web forms


    (Page 3 of 4 )

    Since web forms are the most common mechanism for collecting user data, there is the certain possibility of multiple errors occurring when program control is transferred to users. It is because of this simple but extremely relevant concept  that form validation becomes a critical point within application development.

    Bearing in mind that forms are potentially dangerous, and considering that bad user data can quickly break up an application if wrong assumptions are made, the next thing to do is to build an example that clearly exemplifies the way a simple web form can be used for triggering different errors, and accordingly implementing the appropriate handlers.

    Thus, the first example comprises two sections. First, the “showError()” function, which looks like this:

    function showError(){
      try {
          var data=document.getElementsByTagName('form')[0].elements['data'].value;
          eval(data);
      }
      // catch exceptions
      catch(e){
          var p=document.createElement('p');
          p.appendChild(document.createTextNode('An exception was
    thrown by the script. 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.
    getElementsByTagName&&document.createElement;
        if(W3C){
            document.getElementsByTagName('input')[1].onclick=showError;
        }
    }

    And second, the simple web form for entering data:

    <form method="post">
    <input type="text" name="data" />
    <input type="button" value="Evaluate Code!" />
    </form>

    As you can appreciate, the above example implements a straightforward method for trapping errors that occur when bad data is entered. The “showError()” function wraps up the code responsible for evaluating user input into a “try” block, as depicted below:

      try {
          var data=document.getElementsByTagName('form')[0].elements
    ['data'].value;
          eval(data);
      }

    What the above snippet does is simply execute any string entered on the web form as JavaScript code, through the “eval()” function. Also, I’ve attached an “onclick” event handler to the form button, so the data can be tested without actually submitting the form, but you can easily modify this by introducing another event handler.

    As you’ve learned previously, the “catch” block takes care of catching all raised errors when conflicting data is entered, allowing the display of the script’s output directly on the browser. Of course, real examples are always required, so let’s enter erroneous data through the provided form and see how the generic error handler catches several exceptions.

    First, let’s force a syntax error by entering the following code:

    varb =

    In response to this error (variable declaration is incomplete), the script traps a primary syntax error, by displaying the following message:

    An exception was thrown by the script. Error name :SyntaxError Error message :syntax error

    As with the first case, it’s possible to trigger a range error, by entering something like this:

    var a=new Array(1111222223333444456789)

    Obediently, the script displays the following message:

    An exception was thrown by the script. Error name :RangeError Error message :invalid array length

    In a similar way, a reference error can be deliberately raised, by using a non-existent variable:

    alert(a)

    The above expression raises a reference error, which is trapped and displayed as follows:

    An exception was thrown by the script. Error name :ReferenceError Error message :a is not defined

    The final case illustrates how a type error is trapped, by using the following line of code:

    var a=1;alert(a[1].length);

    For the above example, the script displays the appropriate message:

    An exception was thrown by the script. Error name :TypeError Error message :a[1] has no properties

    Definitely, there are numerous possibilities to explore by entering different fragments of code and studying the corresponding responses triggered by the generic error handler. It’s just a matter of testing each possible form entry.

    Given the previous script, it’s fairly easy to adapt the code for working with input controls other than forms. Thus, in the next few lines, I’ll redefine the “showError()” function for use with built-in JavaScript prompts.

    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 6 hosted by Hostway
    Stay green...Green IT