JavaScript
  Home arrow JavaScript arrow Page 4 - Exception Handling in JavaScript: Introduc...
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: Introduction to Core Concepts
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2005-09-07

    Table of Contents:
  • Exception Handling in JavaScript: Introduction to Core Concepts
  • Exceptional code: introducing the basics of JavaScript exceptions
  • Trapping exceptions: explaining “try-catch” blocks
  • A basic example: handling exceptions through a generic mechanism

  • 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: Introduction to Core Concepts - A basic example: handling exceptions through a generic mechanism


    (Page 4 of 4 )

    In order to illustrate how exceptions can be easily handled in JavaScript, let’s retake the example previously written. First off, here is a listing for the sample “loanCalculator()” function:

    function loanCalculator(loanAmount,loanTerm){

        if(!loanAmount || parseFloat(loanAmount)<10000 || parseFloat(loanAmount)>300000){

            // throw exception

            throw 'Loan amount must be between $10000 and $100000';

        }

        if(!loanTerm || parseInt(loanTerm)<1 || parseInt(loanTerm)>30){

            // throw exception

            throw 'Loan term must be an integer positive value between 1 and 30';

        }

        return parseFloat(loanAmount) / parseInt(loanTerm);

    }

    Now that the function has been defined, let’s wrap up the calling code into a “try-catch” block, like this:

    try{

        var montlyAssesment=loanCalculator(10000,45);

        if(montlyAssesment>300){

            // sorry I can't afford it

        }

        else {

            // that's a bit more affordable

        }

    }

    // catch thrown exceptions

    catch(e){

        if(e=='Loan amount must be between $10000 and $100000'){

            // do something to process this error

            alert(e);

        }

        else if (e=='Loan term must be an integer positive value between 1 and 30'){

            // do something else to process this error

            alert(e);

        }

    }

    As you can see, I’ve purposely called the above function with an invalid argument (loanTerm=45), causing the function to throw an exception within the “try” block, which is trapped by the “catch” statement by using a pair of “if-else if” blocks. In this case, I’ve opted to display the exception itself, but if you find alerts annoying, just modify the code to write down the message directly within the document.

    Notice that the “if-else” blocks contained within the “try” block are never executed because program control is always moved within the “catch” statement, as long as the exception is launched. Of course there is room to play with function arguments and watch how the code reacts, in order to get a clear idea on the transference of program flow.

    By this point, I’ve provided you with all the makings of a simple JavaScript exception handler, being part of the introductory process for implementing exceptions trough efficient programming techniques.

    Wrapping up

    That’s all for the moment. Over this first part of the series, you’ve learned the basics of JavaScript exceptions, together with some explanations of how they can be implemented within a program for your convenience. However, this is only a mere introduction. There are numerous topics to be covered yet.

    In the next part, I’ll be explaining different types of exceptions supported by JavaScript, so you can build up a fine-tuning mechanism to handle them in a more professional way. See you in the next part!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · The first part of the series goes through the explanation of basics exception...
     

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