JavaScript
  Home arrow JavaScript arrow Page 7 - JavaScript Exception Handling
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
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

JavaScript Exception Handling
By: icarus, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 206
    2003-08-14


    Table of Contents:
  • JavaScript Exception Handling
  • Anatomy Of An Exception
  • Playing Catch
  • Being Verbose
  • All For One...
  • The Final Solution
  • Raising The Bar
  • Endzone

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    JavaScript Exception Handling - Raising The Bar
    ( Page 7 of 8 )

    Thus far, you've been working with JavaScript's built-in exceptions, which can handle most logical or syntactical errors. However, JavaScript also allows you to get creative with exceptions, by generating your own custom exceptions if the need arises.

    This is accomplished via JavaScript's "throw" statement, which is used to raise errors which can be detected and resolved by the "try" family of exception handlers. The "throw" statement needs to be passed an error type. When the exception is raised, this exception name and description will be made available to the defined exception handler.

    Let's go to a quick example. In the following piece of code, if the value entered into the form field is greater than 99, the code will manually generate a RangeError exception, which will be caught and displayed appropriately.

    
    <html>
    <head>
    <script language="JavaScript">

    function checkAge()
    {
    try {
    // if incorrect value in form
    // generate an error
    if (document.forms[0].age.value > 99)
    {
    throw RangeError;
    }
    } catch (e) {
    // catch all thrown errors and print error type
    alert(e.name);
    }
    }

    </script>
    </head>

    <body>

    <form>
    <input type="text" name="age" onBlur="checkAge()">
    </form>

    </body>
    </html>

    You can also create your own exceptions, via the JavaScript Error constructor. The following example demonstrates, by creating a custom error type called idiotUserError.

    
    
    

    In this case, when you run the script, a new Error object will be created named idiotUserError, with the message specified in the Error object constructor. This error can now be thrown using the regular "throw" statement, as in the example above.

    Let's try a more useful example:

    
    <html>
    <head>
    <script language="JavaScript">

    // create new Error objects
    badNameError = new Error ("System user name does not match actual user name"); noNameError = new Error ("System user name cannot be blank");

    // create generic exception handler
    // to display error message
    // you may want to filter down error types
    // further inside this and handle each type
    // differently
    function mainExceptionHandler(e)
    {
    alert (e.message);
    }

    // general form validation functions
    function validateForm()
    {
    checkName();
    }

    // check form values
    // if errors, throw appropriate exception
    function checkName()
    {
    try {
    if (document.forms[0].username.value == "")
    {
    throw noNameError;
    }

    if (document.forms[0].username.value != "john")
    {
    throw badNameError;
    }
    } catch (e) {
    // any and all errors will go to this handler
    mainExceptionHandler(e);
    }
    }

    </script>
    </head>

    <body>

    <form onSubmit="validateForm()">
    Enter your system username: <input type="text" name="username"> <br> <input type="submit" name="submit" value="Go"> </form>

    </body>
    </html>

    In this case, if the value entered into the form is blank or not "john", a custom exception will be thrown by the code. This custom exception can be caught by a generic exception handler such as the one used above, and the exception can be routed and resolved appropriately



     
     
    >>> More JavaScript Articles          >>> More By icarus, (c) Melonfire
     

       

    JAVASCRIPT ARTICLES

    - Introduction to JavaScript
    - Adding Elements to a Tree with TreeView jQue...
    - Using the Persist Argument in a TreeView jQu...
    - Using Unique and Toggle in a TreeView jQuery...
    - Using Event Delegation for Mouseover Events ...
    - Using the Animate Option in a Treeview jQuer...
    - Using HTML Lists with Event Delegation in Ja...
    - Opened and Closed Branches on a TreeView jQu...
    - Mouseover Events and Event Delegation in Jav...
    - Creating a TreeView JQuery Hierarchical Navi...
    - Event Delegation in JavaScript
    - A Look at the New YUI Carousel Control
    - Working with Draggable Elements and Transpar...
    - Displaying Pinned Handles with Resizable Con...
    - Building Resizable Containers with the Ext J...





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