JavaScript
  Home arrow JavaScript arrow Page 5 - JavaScript Exception Handling
CIO Insight
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
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: 4 stars4 stars4 stars4 stars4 stars / 150
    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:
      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
     
     
    Iron Speed
     
    ADVERTISEMENT

    Route your faxes to your email inbox. Private, secure fax numbers available from CallWave. Choose your fax number.

    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


       · What about window.onerror?Errors may be any place in code, and this article seem...
       · Here, for your reference, is the meaning of the...
     

       

    JAVASCRIPT ARTICLES

    - Getting Attention with Interactive Effects
    - Interacting with Tooltips and Previews
    - Just-in-Time Information and Ajax
    - Interactive Effects
    - Using Cookies With JavaScript
    - Understanding the JavaScript RegExp Object
    - Controlling Browser Properties with JavaScri...
    - Using Timers in JavaScript
    - Form Validation with JavaScript
    - JavaScript Exception Handling
    - Stringing Things Along
    - Understanding The JavaScript Event Model (pa...
    - Understanding The JavaScript Event Model (pa...
    - An Object Lesson In JavaScript

    Iron Speed



    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway