Java Reference
In-Depth Information
This is the first step in creating a new variation on the TryBlockTest example called TryChainedEx-
ceptions . You can define a new exception class that you will use when an ArithmeticException is
thrown in the divide() method:
public class ZeroDivideException extends Exception {
private int index = -1;
// Index of array element
causing error
// Default Constructor
public ZeroDivideException(){ }
// Constructor that can be chained
public ZeroDivideException(String s, Throwable cause) {
super(s, cause);
// Call the base
constructor
}
// Contructor recording an index value & can be chained
public ZeroDivideException(int index, Throwable cause) {
super(cause);
// 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
}
}
Directory "TryChainedExceptions"
How It Works
You might think that because this exception type is a form of arithmetic exception, it would be advant-
ageous to derive the class from ArithmeticException . Of course, if you did this, the new exception
type would have RuntimeException as an indirect base class, and therefore such exceptions would not
need to be caught. Because you have derived the ZeroDivideException class from the Exception class,
the compiler checks that the exceptions thrown are either caught or identified as thrown in a method.
Your class inherits all the members of the class Throwable via the Exception class, so you get the stack
trace record, the message for the exception, and the ability to record the originating exception for free.
It also inherits the toString() method, which is satisfactory in this context, but you could override this
if desired. The Exception class has five constructors with the same parameters as the Throwable class
constructors. You can therefore to pass a Throwable reference to record the originating exception to the
Search WWH ::




Custom Search