Java Reference
In-Depth Information
Display 9.7
Catching Multiple Exceptions
(part 3 of 3)
Sample Dialogue 2
How many pencils do you have?
−
2
Cannot have a negative number of pencils
End of program.
Sample Dialogue 3
How many pencils do you have?
5
How many erasers do you have?
0
Do not make any mistakes.
End of program.
PITFALL: Catch the More Specific Exception First
When catching multiple exceptions, the order of the
catch
blocks can be important.
When an exception is thrown in a
try
block, the
catch
blocks are examined in order,
and the first one that matches the type of the exception thrown is the one that is exe-
cuted. Thus, the following ordering of
catch
blocks would not be good:
catch
(Exception e)
{
.
.
.
}
catch
(NegativeNumberException e)
{
.
.
.
}
The second
catch
block can
never be reached.
With this ordering, the
catch
block for
NegativeNumberException
would never be
used, because all exceptions are caught by the first
catch
block. Fortunately, the com-
piler will warn you about this. The correct ordering is to reverse the
catch
blocks so
that the more specific exception comes before its parent exception class, as shown in
the following: