Exception handling in Javascript.

Handling execptions statements

Using the try, catch and finally statements

  • The try, catch and finally statement is JavaScript's exception-handling mechanism.
  • A try, catch and finally statement has the form:
     try {
        statements
      } catch (variable) {
        statements
      } finally {
        statements
      }
    Where :
    • The try clause of this statement simply defines the block of code whose exceptions are to be handled.
    • The catch clause is the block of statements that are invoked when an exception occurs anywhere within the try block.
    • The catch clause is followed by a finally block, which normally contains cleanup codes. The finally blocks are optional, but is guaranteed to be executed either an exception or not.
    An example:
    <script type="text/javascript">
      var age = 0;
      try {
        // Execute a function that does not exist;
        age= getAge("Let me know your age: ");
        // This statement will never be executed:
         document.write("Your age is " + age);
      }catch (ex) {  // fetch the error (ex is the error message)
        // Tell the user what the error is
        document.write("<h3 style='color: red;'>"+ex+"</h3>");
      }finally {
        document.write("Maybe I should not asked you about your age.");
      }
    </script>

Using the throw statement.

    To throw an exception is to signal that an error or an exceptional condition.
  • A throw statement has the form:
    throw expression;throw expression;
  • Exceptions are thrown by the system whenever a runtime error occurs and whenever the program explicitly throws one using the throw statement.
    An example:
    <script type="text/javascript">
      var n = 0;
      var approved=false;
      while (!approved) {
        try {
          // Ask the user to enter a number
          n = prompt("To enter an integer between 0 and 10 makes no exceptions.", 0);
          // Compute the factorial of the number, assuming that the user's
          // input is valid
          if (n<=0 || n>=10) {
            throw "Your integer has an error value: "+n;
          }
          // Display the result
          document.write("OK n = " + n+"<br>");
          approved=true;
        }
        catch (ex) {  // If the user's input was not valid, we end up here
          // Tell the user what the error is
          alert(ex);
        }finally {
          if (confirm("Try again?")) { approved=false;
          }else {  approved=true; }
        }
      }
    </script>

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.