Home arrow JavaScript arrow Page 3 - 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 - 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.


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