Chained Exception

This is the feature that allows you to associate the exceptions one to another. the one exception can become the cause of second exception and second exception can become cause of third exception  and so on. So it is called the chaining.

java 1.4 introduced this feature by adding new constructors and methods

New constructors are flowing
public Throwable(String message, Throwable cause)
Constructs a new throwable with the specified detail message and cause.
public Throwable(Throwable cause)
Constructs a new throwable with the specified cause.

New Methods are

public Throwable getCause()
returns the exception object that is cause behind current exception. It there is not exception behind the cause, it will return null.

public Throwable initCause(Throwable cause)
Set the cause of the current exception and returns the reference the reference to the exception. Thus you can associate the cause to the exception after it has been created. The cause of an exception must set one time only.

cause is also an exception object’s reference so you can associates and exception to another exception using initCause() method.

class ChainedExceptions
  static void chain()
    NullPointerException e1=new NullPointerException("e1 Exception");
    ArithmeticException e2=new ArithmeticException("e2 Exception");
    ArrayIndexOutOfBoundsException e3=new ArrayIndexOutOfBoundsException("e3 Exception");
        e3.initCause(new InterruptedException("e4 Exception"));
        throw e1;
    public static void main(String ar[])
           catch(Throwable causes)
              System.out.println("First cause  :"+causes);
              System.out.println("Second Cause :"+causes);
              System.out.println("Third Cause  :"+causes);
              System.out.println("Fourth Cause :"+causes);
        System.out.println("Oparation finished");
First cause  :java.lang.NullPointerException: e1 Exception
Second Cause :java.lang.ArithmeticException: e2 Exception
Third Cause  :java.lang.ArrayIndexOutOfBoundsException: e3 Exception
Fourth Cause :java.lang.InterruptedException: e4 Exception
Oparation finished

in the above program the e3’s exception object has the cause of reference of  object of InterruptedException , e2’s exception object has the cause e3, e1 has the cause e2
And e1 is thrown manually. 

No comments:

Popular Posts