Java | Chained Exceptions

05 min read

Chained Exceptions:

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:

  1. Throwable(Throwable causeExc) //constructors
  2. Throwable(String msg, Throwable causeExc) //constructors
  3. Throwable getCause( ) //Returntypes
  4. 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.

 

getCause( )

  • 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( ).

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error