Exception Chaining or Wrapping Java

Exception chaining concept was introduced with JDK 1.4. Exception chaining permits us to connect the original cause of a problem to the exception actually thrown. Chaining is not generally meant to the user. Chaining is best suitable for the programmer to debug a program by knowing why the basic problem occurred and thus becomes easier to maintain the code.

Sometimes, we come across the following code in Java programming where some exception is caught and another is thrown.

try 
{
  // some code
} 
catch(MyException me) 
{
  throw new OurException();
}

Regrettably, the information message of MyException is lost when OurException is thrown, which complicates debugging to a greater extent. To overcome this problem, the Java designers introduced, in JDK 1.4, a new facility called "Exception chaining" which allows the programmer to wrap one exception in another. It allows the programmer to create an arbitrary chain of exceptions that wraps one exception with another.

To get the concept of exception chaining in a better way, let us take an example of a patient and a doctor. The same disease for different patients may be caused by distinct malfunctions of the body contributed by several risk factors. For example, the heart disease of a patient might be due to genetic hierarchy history, diet deficiencies, smoking, drinking and stress. The patient complains about heart problem. But to cure, the doctor should be aware of the actual cause of the problem that triggered the heart problem; say, stress must be chained to the heart problem. This, in medical terminology, is known as Disease Causal Chain(DiCC). The DiCC can differ from patient to patient. Stress is called backend event and heart problem is called front end event. The doctor cures the actual cause of the disease. Sometimes, DiCC can have big chain which the doctor should be mindful.

Similarly, the programmer should be mindful about the actual cause of the error that may trigger other chain of problems. This is where exception chaining comes into picture.

Advantages of Exception chaining

Following are the two important advantages of the many.

  • It allows us to note the evidence that one exception caused another.
  • It allows knowing the complete information of actual problem and other problems generated due to it by printing "casual chain" of exceptions without much additional effort.

To support the chaining of exceptions, the Java API introduced in JDK 1.4, two new methods in Throwable class, getCause() and initCause(Throwable) and two new constructors Throwable(Throwable) and Throwable(String, Throwable). Other exception classes are also retrofitted with the similar constructors. If any exception does not support these constructors, we can wrap the exceptions using initCause() method. Another new method getStackTrace() enables to stack trace the information provided by the printStackTrace(). The following program, ChainDemo.java, illustrates the chain exceptions.

class ChainDemo    					
{
  public void myMethod1() throws MyException1
  {
    try
    {
      myMethod2();
    }
    catch(MyException2 me)
    {
      System.out.println("In myMethod1() catch block:");
      System.out.println("The Message is " + me.getMessage());
      System.out.println("The cause is " + me.getCause());
      System.out.println();        
      throw new MyException1("The message from myMethod1()", me);
    }   
  }                               
  public void myMethod2() throws MyException2
  {
    try
    {
      myMethod3();
    }
    catch(RuntimeException re)                // super class of ArithmeticException
    {
      System.out.println("In myMethod2() catch block:");
      System.out.println("The Message is " + re.getMessage());
      System.out.println("The cause is " + re.getCause());
      System.out.println();
      throw new MyException2("The message from myMethod2()", re);
    }         
  }         
  public void myMethod3()
  {
    try
    {
      int a=10, b=0, c;
      c = a/b;
    }
    catch(ArithmeticException ae)
    {
      NumberFormatException nfe = new NumberFormatException("The Message from myMethod3()");
      nfe.initCause(ae);
      throw nfe;
    }     
  }
  public static void main(String args[])
  {
    try
    {
      ChainDemo cd1 = new ChainDemo();
      cd1.myMethod1();
    }
    catch(MyException1 me)
    {
      System.out.println("In the main() catch block:");
      System.out.println("The Message is " + me.getMessage());
      System.out.println("The cause is " + me.getCause());
      System.out.println();                  // jut to give a blank line
      System.out.println("To print all the messages from the call stack:");
      me.printStackTrace();
    }
  }
}           

class MyException1 extends Exception         // user-defined exception classes
{
  public MyException1(String m1, Throwable t1) // new  feature of JDK 1.4
  {
    super(m1, t1);                           // calls super class (Exception) matching constructor
  }
}

class MyException2 extends Exception 
{
  public MyException2(String m1, Throwable t1)
  {
    super(m1, t1);
  }
}       

image

View All Exceptions

2 thoughts on “Exception Chaining or Wrapping Java”

Leave a Comment

Your email address will not be published.