Once an application finds an exception, it may respond to it by throwing another exception. While doing so, if the information in the original exception has to be conveyed in the new exception, it can be done by chaining exceptions. Thus, chained exceptions help to associate another exception with an exception where the 2nd exception describes the cause of the 1st exception.
Example: If there is a NumberFormatException and the cause of which is an IOException, the caller of this method may be notified about the cause. This is achieved by making use of chained exceptions.
Constructors & methods useful for creating chained exceptions:
- Throwable(Throwable causeExc) //constructors
- Throwable(String msg, Throwable causeExc) //constructors
- Throwable getCause( ) //Returntypes
- Throwable initCause(Throwable causeExc) //Returntypes
The third and fourth form of Throwable class constructors and the 2 methods — getCause( ) and initCause( ) play a major role in chaining exceptions.
- Returns the exception that underlies the current exception. If no underlying exception exists, null is returned.
initCause (Throwable causeExc)
- Associates causeExc with the invoking exception and returns a reference to the exception. This can be called only once for each exception object.
If the cause Exception was set by a constructor, then it cannot be set again using initCause( ).