This was introduced in JavaScript 1.4 and JScript version 5.0. The intention is to provide a way to execute a section of code in the try block and then if it has a problem, some recovery action can trap the error and handle it gracefully.
There are three basic sections.
The try statement is followed by a block of code enclosed in braces that may be problematic. Indeed, the problems may not be script-based errors but may be the result of testing for some condition. That may lead to a custom exception being thrown.
If an exception of any kind happens in the try block, execution is immediately passed to the catch() function following.
The catch function is passed an Error object containing details of the kind of exception that has occurred.
When the catch function completes, execution drops into the block of code associated with the finally statement. In the case of the try block not having any exceptional behavior, at the end of that block execution also drops into the finally code block, bypassing the catch function altogether. So the finally code gets executed always after the try block.
You might use the finally block to tidy up or discard some unwanted objects.
In the example, the try block makes sure two values are presented in the correct order. If they are not in the right order, an exception is thrown and during the exception handling, they are swapped over. We put up an alert and set a flag that is presented in the output just to be sure it really happened like that.
The functionality is not supported in Netscape prior to version 6.0.
This is not supported by Netscape Enterprise Server 3 and so its error handling capabilities are not available server-side.
<HTML> <HEAD> </HEAD> <BODY> <SCRIPT> testThrow(100, 200); testThrow(300, 100); function testThrow(arg1, arg2) { var switched = "NO"; // Force an error condition try { if(arg1 < arg2) { throw "Wrong order"; } } catch(myErr) { alert(myErr); var temp = arg1; arg1 = arg2; arg2 = temp; switched = "YES" } finally { document.write("Biggest : " + arg1 + "<BR>"); document.write("Smallest : " + arg2 + "<BR>"); document.write("Switched : " + switched + "<BR>"); document.write("<BR>"); } } </SCRIPT> </BODY> </HTML>
ECMA 262 edition 2 - section - 7.4.3
ECMA 262 edition 3 - section - 7.5.2
ECMA 262 edition 3 - section - 12.14
Prev | Home | Next |
true | Up | TT object |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |