Using the trycatch Statement


Using the try catch Statement

When you enclose a series of statements in a try statement, any error that happens when executing those statements will throw (that is, cause) an exception . When an exception is thrown, JavaScript will terminate the try statement and look for a catch statement, which "catches" the exception. If there is a catch statement, the code in that catch statement is executed, enabling you to deal with the error. There is also an optional finally statement, which is executed whether or not an exception occurs; here's the syntax:

 try {  tryStatements  }  [catch (  exception  )      {  catchStatements  }]  [finally {finallyStatements}] 

The following parts comprise these statements:

  • tryStatements . A set of statements that executes once. If these statements throw an exception, execution transfers to a catch statement if there is one.

  • exception . The name of the variable you want to use to hold the object (usually an Error object) passed to the catch statement.

  • catchStatements . A set of statements that executes if an exception was thrown.

  • finallyStatements . A set of statements that is executed before the try catch statement completes. These statements execute whether or not an exception was thrown or caught.

The try catch statement is relatively new, as you see in Table 3.17.

Table 3.17. The try catch Statement

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

Try catch

     

x

     

x

x

x

Let's put the try catch statement to work now.

Unconditional catch Statements

When an exception occurs, execution transfers to the catch statement, if there is one. For example, we might cause the same error as in our onerror examplebut this time, we'll use a try catch statement. That means we place the error- causing code in a try statement and display the message There was an error. in the catch statement, as follows :

(Listing 03-20.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Reporting an Error          </TITLE>      </HEAD>      <BODY>          <H1>Reporting an Error</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--  try {   var myData = undefinedVariable   }   catch(e) {   document.write("There was an error.")   }  // -->          </SCRIPT>       </BODY>  </HTML> 

Figure 3.17 shows this code at work.

Figure 3.17. Using try catch to catch an exception.

graphics/03fig17.gif

The simple message There was an error. doesn't tell the user very much, however. The object that's passed to us in a catch statement is an Error object, and we can tell the user the name of the error by using this object's name property. The JavaScript error names are EvalError , RangeError , ReferenceError , SyntaxError , TypeError and URIError .

Tip

Other objects can throw their own error types in JavaScript. For example, W3C DOM objects can throw exceptions such as HIERARCHY_REQUEST_ERROR , WRONG_DOCUMENT_ERROR , NO_MODIFICATION_ALLOWED_ERROR , and so on.


In the parentheses following the catch keyword, you can assign a name to the Error object passed to the catch statement; in this example, following standard usage, I'll just call that object e :

 try {      var myData = undefinedVariable  }  catch(e) {  document.write("There was an error.")  } 

Now, in the catch statement, we can find the name of the error that occurred with the e.name property, so here's how we let the user know what error happened :

(Listing 03-21.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Reporting an Error's Name          </TITLE>      </HEAD>       <BODY>          <H1>Reporting an Error's Name</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--             try {                  var myData = undefinedVariable              }  catch(e) {   document.write("An error of type " + e.name + " occurred.")   }  // -->          </SCRIPT>       </BODY>  </HTML> 

You can see this new, improved version of this example in Figure 3.18.

Figure 3.18. Reporting an exception's name.

graphics/03fig18.gif

Conditional catch Statements

Because you can determine the type of an error using the Error object's name property, you can add code to handle specific types of errors. Here's an example, where I'm using a switch statement to handle different types of exceptions:

(Listing 03-22.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Handling Specific Errors          </TITLE>      </HEAD>      <BODY>          <H1>Handling Specific Errors</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--             try {                  var myData = undefinedValue              }              catch (e){  switch (e.name){   case "EvalError":   document.write("An EvalError error occurred.")   break   case "RangeError":   document.write("A RangeError error occurred.")   break   case "ReferenceError":   document.write("A ReferenceError error occurred.")   break   case "SyntaxError":   document.write("A SyntaxError error occurred.")   break   case "TypeError":   document.write("A TypeError error occurred.")   break   case "URIError":   document.write("An URIError error occurred.")   break   default:   document.write("An error occurred.")  }              }          / / -->          </SCRIPT>       </BODY>  </HTML> 

In this case, I'm just displaying the type of exception that occurred; in your own code, however, you could write code to actually handle and recover from the error. This example depends on using the name property of the Error object, which is a very useful property, but note that the Error object has other properties as well.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net