Java Reference
In-Depth Information
System.out.println();
}
Directory "TryChainedExceptions"
You should put the
TryChainedExceptions
class file and the file for the
ZeroDivideException
class
together in the same directory.
The output from this example includes:
Values: 10 5 0 3 12 0 6
First try block in main()entered
... more output
First try block in divide() entered
Arithmetic exception caught in divide()
Throwing ZeroDivideException
ZeroDivideException caught in main()
ZeroDivideException: java.lang.ArithmeticException: / by zero
at TryChainedExceptions.divide(TryChainedExceptions.java:49)
at TryChainedExceptions.main(TryChainedExceptions.java:16)
Caused by: java.lang.ArithmeticException: / by zero
at TryChainedExceptions.divide(TryChainedExceptions.java:43)
... 1 more
Zero divisor at x[2] corrected to 1
Outside first try block in main()
... more output
First try block in divide() entered
Index-out-of-bounds index exception caught in divide()
Executing code after try block in divide()
result = 1
Outside first try block in main()
First try block in main()entered
... more output
Outside first try block in main()
Values: 0 5 2 0 12 1 12
How It Works
The
main()
method creates an array of integers and iterates over the elements in the
for
loop. The
di-
vide()
method is called in a
try
block, so any exceptions throw by
divide()
can be caught in
main()
.
The
divide()
methods sets the value of the array element corresponding to the index value that is
passed. The value is the ratio of elements at
index+2
and
index+1
. When the divisor is zero, an
Arith-
meticException
is thrown and caught by the
catch
block in
divide()
.
The
catch
block for
ArithmeticException
creates an instance of the new exception class
Zer-
oDivideException
and passes the index for the element with the zero value and the reference to the
ArithmeticException
to the constructor. The new exception is thrown to notify the calling program,
main()
.