Java Reference
In-Depth Information
import java.io.IOException;
public class TryBlockTest {
public static void main(String[] args) {
// Code for main()..
}
// Divide method
public static int divide(int[] array, int index) {
// Code for divide()...
}
}
TryBlockTest.java
The idea behind the
divide()
method is to pass it an array and an index as arguments. By choosing
the values in the array and the index value judiciously, you are able to cause exceptions of type
Arith-
meticException
and
ArrayIndexOutOfBoundsException
to be thrown. You use a
try
block plus two
catch
blocks for the exceptions, and you throw in a
finally
block for good measure. Here's the code
for
divide()
:
public static int divide(int[] array, int index) {
try {
System.out.println("\nFirst try block in divide() entered");
array[index + 2] = array[index]/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()");
System.out.println("index = " + index +
" Expression: " + "array[" + index + "]/array["+ (index+1)
+"] is " +
array[index] + "//" +
array[index+1]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index-out-of-bounds exception caught in
divide()");
System.out.println("array length = " + array.length +
" index = " +
index);
} finally {
System.out.println("finally block in divide()");
}