Java Reference
In-Depth Information
require knowledge of the exact failure, so they will want to have that
information availablesee "
Stack Traces
"
on page
294
.
Situations like this are common enough that the exception mechanism
includes the notion of one exception being
caused
by another exception.
The
initCause
method, defined in
Throwable
, sets one exception's cause
to be the exception object passed as a parameter. For example, the pre-
vious example can have its
IOException
catch clause rewritten as:
} catch (IOException e) {
BadDataSetException bdse = new BadDataSetException();
bdse.initCause(e);
throw bdse;
} finally {
// ...
}
Here
initCause
is used to remember the exception that made the data
bad. This means that the invoking code can handle all bad data simply
with one exception handler but still know the kind of exception that
caused the underlying problem. The invoking code can use the
getCause
method to retrieve the exception.
The example can be simplified further by writing
BadDataSetException
to
expect to have a cause, at least some of the time, and so provide a con-
structor to accept that cause if it is known. The idiomatic way to define a
new exception class is to provide at least the following four constructor
formsor variants thereof that deal with exception specific data:
class BadDataSetException extends Exception {
public BadDataSetException() {}
public BadDataSetException(String details) {
super(details);
}
public BadDataSetException(Throwable cause) {