Friday, 24 January 2014

CHAINED EXCEPTIONS IN JAVA

What are the Chained Exceptions  Used 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 one exception causes another.Chained Exceptions help the programmer do this.Exception chaining, or exception wrapping, is an object-oriented programming technique of handling exceptions by re-throwing a caught exception after wrapping it inside a new exception. The original exception is saved as a property (such as cause) of the new exception.

The following example shows how to use a chained exception:

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.

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 exception. getCause returns the exception that caused the current exception, and initCause sets the current exception's cause.








No comments :

Post a Comment