6.17. try/catch/finallyThe TRy/catch/finally statement is JavaScript's exception-handling mechanism. The TRy clause of this statement simply defines the block of code whose exceptions are to be handled. The try block is followed by a catch clause, which is a block of statements that are invoked when an exception occurs anywhere within the TRy block. The catch clause is followed by a finally block containing cleanup code that is guaranteed to be executed, regardless of what happens in the try block. Both the catch and finally blocks are optional, but a try block must be accompanied by at least one of these blocks. The TRy, catch, and finally blocks all begin and end with curly braces. These braces are a required part of the syntax and cannot be omitted, even if a clause contains only a single statement. Like the tHRow statement, the try/catch/finally statement is standardized by ECMAScript v3 and implemented in JavaScript 1.4. The following code illustrates the syntax and purpose of the TRy/catch/finally
Here is a realistic example of the try/catch statement. It uses the factorial( ) method defined in the previous section and the client-side JavaScript methods prompt( ) and alert( ) for input and output:
This example is a try/catch statement with no finally clause. Although finally is not used as often as catch, it can often be useful. However, its behavior requires additional explanation. The finally clause is guaranteed to be executed if any portion of the try block is executed, regardless of how the code in the try block completes. It is generally used to clean up after the code in the try clause. In the normal case, control reaches the end of the try block and then proceeds to the finally block, which performs any necessary cleanup. If control leaves the try block because of a return, continue, or break statement, the finally block is executed before control transfers to its new destination. If an exception occurs in the try block and there is an associated catch block to handle the exception, control transfers first to the catch block and then to the finally block. If there is no local catch block to handle the exception, control transfers first to the finally block and then propagates up to the nearest containing catch clause that can handle the exception. If a finally block itself transfers control with try and finally can be used together without a catch clause. In this case, the finally block is simply cleanup code that is guaranteed to be executed, regardless of any break, continue, or return statements within the try clause. For example, the following code uses a try/finally
|
Friday, October 23, 2009
Section 6.17. try/catch/finally
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment