Java Reference
In-Depth Information
At the core of exception handling are
try
and
catch
. These keywords work together; you
can't have a
catch
without a
try
. Here is the general form of the
try
/
catch
exception hand-
ling blocks:
Here,
ExcepType
is the type of exception that has occurred. When an exception is thrown,
it is caught by its corresponding
catch
statement, which then processes the exception. As
the general form shows, there can be more than one
catch
statement associated with a
try
.
The type of the exception determines which
catch
statement is executed. That is, if the ex-
ception type specified by a
catch
statement matches that of the exception, then that
catch
statement is executed (and all others are bypassed). When an exception is caught,
exOb
will
receive its value.
Here is an important point: If no exception is thrown, then a
try
block ends normally,
and all of its
catch
statements are bypassed. Execution resumes with the first statement fol-
lowing the last
catch
. Thus,
catch
statements are executed only if an exception is thrown.
NOTE
Beginning with JDK 7, there is another form of the
try
statement that supports
automatic
resource management
. This form of
try
is called
try
-with-resources
. It is described in
Chapter 10
,
in the context of managing I/O streams (such as those connected to a file) be-
cause streams are some of the most commonly used resources.