Java Reference
In-Depth Information
Try It Out - Define Your Own Exception Class
We can define the class which will correspond to an ArithmeticException in the method
divide() as:
public class ZeroDivideException extends Exception {
private int index = -1; // Index of array element causing error
// Default Constructor
public ZeroDivideException(){ }
// Standard constructor
public ZeroDivideException(String s) {
super(s); // Call the base constructor
}
public ZeroDivideException(int index) {
super("/ by zero"); // Call the base constructor
this.index = index; // Set the index value
}
// Get the array index value for the error
public int getIndex() {
return index; // Return the index value
}
}
How It Works
As we've derived the class from the class Exception , the compiler will check that the exceptions
thrown are either caught, or identified as thrown in a method. Our class will inherit all the members of
the class Throwable via the Exception class, so we'll get the stack trace record and the message for
the exception maintained for free. It will also inherit the toString() method which is satisfactory in
this context, but this could be overridden if desired.
We've added a data member, index , to store the index value of the zero divisor in the array passed to
divide() . This will give the calling program a chance to fix this value if appropriate in the catch
block for the exception. In this case the catch block would also need to include code that would enable
the divide() method to be called again with the corrected array.
Let's now put it to work in our first TryBlockTest code example.
Try It Out - Using the Exception Class
We need to use the class in two contexts - in the method divide() when we catch a standard
ArithmeticException , and in the calling method, main() , to catch the new exception. Let's
modify divide() first:
public static int divide(int[] array, int index) throws ZeroDivideException {
try {
System.out.println("First try block in divide() entered");
array[index + 2] = array[index]/array[index + 1];
Search WWH ::




Custom Search