try...catch

Marks a block of statements to try, and specifies a response should an exception be thrown.

Syntax

try
{
statements
}
[catch (catchID)
{
statements
}]
[finally
{
statements
}]\

Parameters

Parameter Description
statements Block of statements that executes once. The statements can be declarative statements (such as var) or executable statements (such as for).
catch A block of statements to be executed if an exception is thrown in the try block.
catchID An identifier to hold an exception object.
finally A block of statements that is executed before the try...catch statement completes. This block of statements executes whether or not an exception was thrown or caught.

Description

The try...catch statement consists of a try block, which contains one or more statements, and a catch block, containing statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block. If no exception is thrown in the try block succeed, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try...catch statement.
You can nest one or more try...catch statements. If an inner try...catch statement does not have a catch block, the enclosing try...catch statement's catch block is entered.

The catch Block

The catch block is entered when any exception is thrown. For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.

The catch Block's Identifier

When an exception is thrown in the try block, the catchID holds the value specified by the throw statement; you can use this identifier to get information about the exception that was thrown. MetaScript creates this identifier when the catch block is entered; the identifier lasts only for the duration of the catch block; after the catch block finishes executing, the identifier is no longer available.

The finally Block

The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.
You can use the finally block to make your script fail gracefully when an exception occurs; for example, you may need to release a resource that your script has tied up.

Examples

See the examples for throw.

See also

throw


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.