try...catch : try catch : Statement JAVASCRIPT TUTORIALS


JAVASCRIPT TUTORIALS » Statement » try catch »

 

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>







HTML code for linking to this page:

Follow Navioo On Twitter

JAVASCRIPT TUTORIALS

 Navioo Statement
» try catch