Java Reference
In-Depth Information
}
Directory "TryChainedExceptions"
Note the throws clause in the method definition. Without this you will get an error message from the
compiler. The statements in the catch block for ArithmeticException creates and throws a new ex-
ception.
This new exception needs to be caught in the calling method main() :
public static void main(String[] args) {
int[] x = {10, 5, 0, 3, 12, 0, 6};
// Array of integers
System.out.print("Values: ");
for(int xValue : x) {
System.out.print(" " + xValue);
}
System.out.println();
for(int i = 0 ; i < x.length ; ++i) {
// This block only throws an exception if method divide() does
try {
System.out.println("First try block in main()entered");
System.out.println("result = " + divide(x,i));
} catch(ZeroDivideException e) {
System.out.println("\nZeroDivideException caught in main()");
int index = e.getIndex();
// Get the index for the error
if(index > 0) {
// Verify it is valid and now fix
the array
x[index] = 1; // ...set the divisor to 1...
x[index + 1] = x[index - 1]; // ...and set the result
e.printStackTrace();
System.err.println("Zero divisor at x[" + index + "]
corrected to " +
x[index]);
}
} catch(ArithmeticException e) {
System.out.println("Arithmetic exception caught in main()");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index-out-of-bounds exception caught in
main()");
}
System.out.println("Outside first try block in main()");
}
System.out.print("Values: ");
for(int xValue : x) {
System.out.print(" " + xValue);
}
Search WWH ::




Custom Search