JavaScript
  Home arrow JavaScript arrow Page 5 - 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? 
Google.com  
JAVASCRIPT

JavaScript Exception Handling
By: icarus, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 207
    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 - All For One...
    ( Page 5 of 8 )

    You can also write specific exception handlers for different types of exceptions, by using an "if" test to check the exception type within the "catch" block. Consider the following handler, which only handles TypeError exceptions:

    
    <script language="JavaScript">

    try {
    colours[2] = "red";
    } catch (e) {
    if (e instanceof TypeError)
    {
    alert("Bad or undefined variable!");
    }
    }

    </script>

    Here's the output:

    Bad or undefined variable!

    Of course, this handler will now only restrict its activities to TypeError exceptions. All other errors will be ignored.

    The JavaScript 1.5 specification defines six primary error types, as follows:

    EvalError - raised when the eval() functions is used in an incorrect manner;

    RangeError - raised when a numeric variable exceeds its allowed range;

    ReferenceError - raised when an invalid reference is used;

    SyntaxError - raised when a syntax error occurs while parsing JavaScript code;

    TypeError - raised when the type of a variable is not as expected;

    URIError - raised when the encodeURI() or decodeURI() functions are used in an incorrect manner;

    You can trap more than one exception, and handle each one in a different way, by using multiple "if" constructs within a single "catch" block.

    
    try {
    execute this block
    } catch (error) {
    if (error instanceOf errorType1)
    {
    do this
    }
    else if (error instanceOf errorType2)
    {
    do this
    }
    
    ... and so on ...
    
    else
    {
    do this if none of the error types above match
    }
    } 
    

    If an exception is encountered while running the code within the "try" block, the JavaScript interpreter stops execution of the block at that point and begins checking each "if" test within the "catch" block to see if there is a handler for the exception. If a handler is found, the code within the appropriate "if" block is executed; if not, control moves to the "else" block, if one exists.

    Once the "try" block has been fully executed and assuming that the program has not been terminated, the lines following the "try" block are executed.

    Take a look at the next example, which demonstrates how this works by revising the example on the previous page::

     
    <script language="JavaScript">

    // ask for user input
    code = prompt("Enter some JavaScript code");

    // run the code and catch errors if any generated
    try {
    eval(code);
    } catch (e) {
    if (e instanceof TypeError)
    {
    alert("Variable type problem, check your variable definitions!")
    }
    else if (e instanceof RangeError)
    {
    alert("Number out of range!")
    }
    else if (e instanceof SyntaxError)
    {
    alert("Syntax error in code!");
    }
    else
    {
    alert("An unspecified error occurred!");
    }
    }

    </script>

    You can test this exception handler by entering different lines of code into the box that appears when you load the page into your browser.

    * To generate a TypeError, try accessing a non-existent array subscript, like this:

    
    alert(someArr[18])
    

    * To generate a RangeError, try creating an array with an extremely large size, like this:

    
    var someArr = new Array(89723742304323248456)
    

    * To generate a SyntaxError, try entering a line of code with a deliberate error in it, like this:

    
    vara count = 99
    

    As you will, in each case, the exception handler above will identify the error type and display an appropriate alert message. The "else" block works as a catch-all exception handler, processing all errors which have not been accounted for in the preceding "if" clauses.



     
     
    >>> 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 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek