Java Reference
In-Depth Information
identifying the problem (by having more than one exception type or by providing additional data within the
new exception type). For example, you could define more than one exception class of your own that repres-
ents an
ArithmeticException
, where each reflected the specifics of a particular situation. This situation is
illustrated in
Figure 7-7
. The numbers on the arrows indicate the sequence.
differentiated in the calling method,
method1()
. The
method2()
method can throw an exception either of
type
Exception1
or of type
Exception2
, depending on the analysis that is made in the
catch
block for the
ArithmeticException
type. The calling method has a separate
catch
block for each of the exceptions that
may be thrown.
You could also define a new exception class that had instance variables to identify the problem more pre-
cisely. Let's suppose that in the last example you wanted to provide more information to the calling program
about the error that caused each exception in the
divide()
method. The primary exception can be either an
ArithmeticException
or an
ArrayIndexOutOfBoundsException
, but because you're dealing with a spe-
cific context for these errors, you could give the calling program more information by throwing your own
exceptions.
It would also make sense to make your exceptions chained exceptions that also recorded the originating
exception. Let's take the
ArithmeticException
case as a model and define an exception class to use in the
program to help identify the reason for the error more precisely. This is just for illustration purposes and is
not intended to imply that you need to catch exceptions of type
ArithmeticException
.
TRY IT OUT: Chaining Exceptions