A
try expression consists of a body, zero or more
catch clauses, and an optional
finally clause. The body is executed until it finishes or a
Exception is thrown. A
catch clause has a formal parameter declaration that specifies a
Exception type. If a
Exception is thrown out of the body before the body completes, the catch clauses are examined in order, and the first one whose variable type is compatible with the thrown value (as determined by
isa) will be executed with the variable set to the caught value. The type of each catch clause variable must be a subtype of
Exception and may not be a subtype of a previous catch clause variable.
The
finally clause, if present, will always be executed after the body and any catch body, regardless of whether the body finished normally or not.
As of version 4.0 of the API, the
try statement may produce a value based on its body and
catch clause bodies but excluding the
finally body. Just as with
switch, a value will only be produced if the last statement of
body and every
catch-body either produces a value, throws an exception or returns. If the
body executes without an exception being caught, then its final statement produces the value, otherwise the final statement of the
catch clause body produces the value.
If a
catch or
finally clause itself throws a
Exception, the current
try expression is exited. Such a
Exception may be caught by an outer nested
try expression.
As of version 4.0 of the API, the
return,
break, and
continue statements may be used to transfer control out of a
try expression. They cannot, however, transfer control out of a
finally block, as there may be an exception waiting to be rethrown as soon as the
finally block finishes executing.