Java Reference
In-Depth Information
12.4.
TRy
,
catch
, and
finally
You catch exceptions by enclosing code in
TRy
blocks. The basic syntax
for a
TRy
block is:
try {
statements
} catch (
exception_type1 identifier1
) {
statements
} catch (
exception_type2 identifier2
) {
statements
...
} finally {
statements
}
where either at least one
catch
clause, or the
finally
clause, must be
present. The body of the
try
statement is executed until either an excep-
tion is thrown or the body finishes successfully. If an exception is thrown,
each
catch
clause is examined in turn, from first to last, to see wheth-
er the type of the exception object is assignable to the type declared in
the
catch
. When an assignable
catch
clause is found, its block is executed
with its identifier set to reference the exception object. No other
catch
clause will be executed. Any number of
catch
clauses, including zero, can
be associated with a particular
TRy
as long as each clause catches a dif-
ferent type of exception. If no appropriate
catch
is found, the exception
percolates out of the
try
statement into any outer
try
that might have a
catch
clause to handle it.
If a
finally
clause is present with a
try
, its code is executed after all other
processing in the
try
is complete. This happens no matter how comple-
tion was achieved, whether normally, through an exception, or through a
control flow statement such as
return
or
break
.