Java Reference
In-Depth Information
base class constructor, so the ArithmeticException that was originally thrown is still available from
your exception object.
You've added a data member, index , to store the index value of the zero divisor in the array passed to
divide() . This gives the calling program a chance to fix this value if appropriate in the catch block
for the exception. This might arise in an application with data that might be logged automatically in a
manufacturing plant for example, where because of the conditions, some erroneous data is to be expec-
ted. In this case, the catch block needs to include code that enables the divide() method to be called
again with the corrected array to reprocess the data. There may be circumstances where the index cannot
be supplied. In this case the default value that is an invalid index value will allow code that catches the
exception to determine when this is the case.
Let's now put it to work in the TryChainedExceptions example.
TRY IT OUT: Using Chained Exceptions
The computations in this example are completely arbitrary and have been contrived so that exceptions
will be thrown. The TryChainedExceptions class defines two static methods, main() and divide() .
You'll use the new exception class in two contexts — in the divide() method when you catch a standard
ArithmeticException and in the calling method main() to catch the new exception. Let's define the
divide() method first:
public static int divide(int[] array, int index) throws
ZeroDivideException {
try {
System.out.println("\nFirst try block in divide() entered");
array[index] = array[index+2]/array[index + 1];
System.out.println("Code at end of first try block in
divide()");
return array[index + 2];
} catch(ArithmeticException e) {
System.out.println("Arithmetic exception caught in divide()");
ZeroDivideException zde = new ZeroDivideException(index + 1, e);
System.out.println("Throwing ZeroDivideException");
throw zde;
// Throw the new
exception
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println(
"Index-out-of-bounds index exception caught in
divide()");
}
System.out.println("Executing code after try block in divide()");
return array[index];
}
Search WWH ::




Custom Search