try...catch : try catch « Statement « JavaScript Tutorial

Home
JavaScript Tutorial
1.Language Basics
2.Operators
3.Statement
4.Development
5.Number Data Type
6.String
7.Function
8.Global
9.Math
10.Form
11.Array
12.Date
13.Dialogs
14.Document
15.Event
16.Location
17.Navigator
18.Screen
19.Window
20.History
21.HTML Tags
22.Style
23.DOM Node
24.Drag Drop
25.Object Oriented
26.Regular Expressions
27.XML
28.GUI Components
29.Dojo toolkit
30.jQuery
31.Animation
32.MS JScript
JavaScript Tutorial » Statement » try catch 
3.13.1.try...catch

Syntax

try{
        statement1
    }catch(exception){
        statement2
    }

It can be used to handle all or some of the errors that can occur in a script.

If an error is not handled by a try...catch statement, it is passed on so other statements can handle the error.

If there are no other statements to handle the error, it is passed to the browser to handle.

statement1 is where an error can occur, while statement2 is used to handle the error.

As soon as an error occurs, the value thrown is passed to the catch portion of the statement and stored in exception.

If the error can not be handled, another throw statement is used to pass the error to a higher level handler if one is defined.

It is possible to have nested try...catch statements within try...catch statements.

The following example uses a try...catch Statement to Handle an Incorrect Entry.

<html>
    <head>
      <title>Using a try..catch statement</title>
    <script language="JavaScript">
    <!--
    function myErrorHandler(data){
      try{
        try{
          if(data == "string"){
            throw "E0";
          }else{
            throw "E1";
          }
        }catch(e){
          if(e == "E0"){
            return("Error (" + e + "): Entry must be numeric.");
          }else{
            throw e;
          }
        }
      }catch (e){
        return("Error (" + e + "): Entry was invalid.");
      }
    }
    function processData(form){
      if(isNaN(parseInt(form.myText.value))){
        alert(myErrorHandler("string"));
      }else{
        alert("You have correctly entered a number");
      }
    }
    -->
    </script>
    </head>
    <body>
    <form name="myForm">
      Please enter a number:
      <input type=TEXT size=10 value="" name="myText">
      <input type=BUTTON value="Process" name="myButton" onClick='processData(this.form)'>
    </form>
    </body>
    </html>
3.13.try catch
3.13.1.try...catch
3.13.2.Catch that error
3.13.3.Exception handling with try/catch
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.