Java Reference
In-Depth Information
Figure 9-3.
The class hierarchy for Exception1, Exception2, and Exception3 exception classes
Consider the following
try-catch
block:
try {
// Exception1, Exception2 or Exception 3 could be thrown here
}
catch (Exception1 e1) {
// Handle Exception1
}
catch (Exception2 e2) {
// Handle Exception2
}
catch (Exception3 e3) {
// Handle Exception3
}
If you try to apply the steps to find an appropriate
catch
block, the above snippet of code would always execute
the first
catch
block, irrespective of the type of exception thrown (
Exception1
,
Exception2
, or
Exception3
) from the
try
block. This is because
Exception1
is the direct/indirect superclass of
Exception2
and
Exception3
. The above
snippet of code shows a logical mistake made by the developer. The Java compiler is designed to handle this kind
of logical mistake that you might make and it generates a compile-time error. You must apply the following rule for
arranging multiple
catch
blocks for a
try
block:
Multiple catch blocks for a
try
block must be arranged from the most specific exception type to the
most generic exception type. Otherwise, a compile-time error occurs. The first
catch
block should
handle the most specific exception type and the last the most generic exception type.