Java Reference
In-Depth Information
super(cause);
}
public BadDataSetException(String details,
Throwable cause) {
super(details, cause);
}
}
Now the catch clause in the example simply becomes:
} catch (IOException e) {
throw new BadDataSetException(e);
} finally {
// ...
}
Not all exception classes provide cause-taking constructors, but all sup-
port the
initCause
method. To make it easier to use
initCause
with such
exception classes, it returns the exception instance that it is invoked on.
The idea is that you can use it like this:
throw new BadDataSetException().initCause(e); // Error?
The only problem is that this will nearly always result in a compile-time
error:
initCause
returns a
THRowable
instance, and you can only throw a
THRowable
if your method's
throw
clause lists
Throwable
which it rarely, if
ever, should! Consequently, you have to modify the above, to cast the
Throwable
back to the actual exception type you are creating:
throw (BadDataSetException)
new BadDataSetException().initCause(e);