MY mENU


Friday, 10 February 2012

Chained Exception in Java


An application often responds to an Exception by throwing another Exception. In effect, the first Exception causes the second Exception. It can be very helpful to know when oneException causes another.

Chained Exceptions help the programmer do this.

The following are the methods and constructors in Throwable that support Chained Exceptions.

Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)

The Throwable argument to initCause and the Throwable constructors is the Exception that caused the current ExceptiongetCause returns the Exception that caused the currentException, and initCause returns the current Exception.

Example :


try {

} catch (IOException e) {
throw new SampleException("Other IOException", e);
}

In this example, when an IOException is caught, a new SampleException Exception is created with the original cause attached and the chain of Exceptions is thrown up to the next higher level Exception handler.

No comments:

Post a Comment