Try statement

It branches execution depending on an exception.


Table of contents:


Format

try

catch

Scope

Reserved variable

Statement

endtry

Example

Format

The format is:


try

...

catch

...

endtry


The execution moves to the catch section if an exception occurs in the try section. If without the catch section, execution moves to the next of the endtry.

When the execution reaches the catch or endtry without any exception, execution moves to the next of the endtry.

try

A keyword that indicates that it is a try statement and the start of a try section.

The try section is:


try

...


Only one try section is required at the beginning of the try statement.

catch

A keyword that indicates that the start of a catch section.

The catch section is:


catch

...


If an exception occurs in the try section, statements in this section will be executed unconditionally.

When the execution reaches the endtry, the execution moves to the next to the endtry.

If an exception occurs again in the catch section, the exception is thrown to outside of the current try statement.


The catch section is optional. There can be only one in the statement.

If there is no catch section, an exception occurred in the try section will be considered handled unconditionally.

Scope

There is no scope for entire try statement. Sections generate separate scopes.

Reserved variable

When execution reaches into the catch section, a scope is generated and reserved variable __error is defined.

__error is a variable of the error class. It will be initialized with an exception occurred in the try section.

Statement

Statements within a section are optional. You can place statements as many as you want.

endtry

This is a keyword that indicates the end of the try statement.

You can use the abbreviation "et" instead of "endtry". Note that "et" is also a keyword.

Example

1:

class example

2:

open method void someMethod()

3:

throw "exception";

4:

em

5:

ec

1:

example ex;

2:

try

3:

ex.someMethod(); // It throws an exception.

4:

catch

5:

string mess = __error.ExceptionData.Entity; // "exception"

6:

endtry

An exception is thrown from the someMethod().


The exception is caught by the try statement, and the execution moves into the catch section.

When execution moves into the catch section, the reserved variable __error has stored the thrown exception.

Copyright © Rice All rights reserved.