Java Reference
In-Depth Information
As the output confirms, each
catch
statement responds only to its own type of exception.
In general,
catch
expressions are checked in the order in which they occur in a program.
Only a matching statement is executed. All other
catch
blocks are ignored.
Catching Subclass Exceptions
There is one important point about multiple
catch
statements that relates to subclasses. A
catch
clause for a superclass will also match any of its subclasses. For example, since the
superclass of all exceptions is
Throwable
, to catch all possible exceptions, catch
Throw-
able
. If you want to catch exceptions of both a superclass type and a subclass type, put the
subclass first in the
catch
sequence. If you don't, then the superclass
catch
will also catch
all derived classes. This rule is self-enforcing because putting the superclass first causes
unreachable code to be created, since the subclass
catch
clause can never execute. In Java,
unreachable code is an error.
For example, consider the following program:
The output from the program is shown here: