by Dinesh Thakur

Sometimes a catch block catches one exception type and then throws a new exception with additional information. This is known as chained exception. This feature allows you to associate another exception with an exception. The second exception describes the cause of the firstexception.

For example, suppose you try to read a number from the disk and use it to divide a number. Now think that a method throws ArithmeticExeption exception because of an attempt to divide by zero. But actually the problem occurred due to incorrect I/O which caused divisor to be set improperly (i.e. set to 0). Although method must certainly throw an ArithmeticExeption exception but in addition it must let the calling method know that some information about actual cause of error. This is where chained exception comes into picture.

 

public class ChainedException

{
       static void B() throws Exception
        {
           throw new Exception("Exception thrown in method B");
        }
         static void A() throws Exception
        {
            try
             {
                 B();
             }
             catch(Exception e)
             {
                  throw new Exception("Exception throws in method A",e);
              }
        }
        public static void main(String[] args)
        {
              try
              {
                      A();
               }
              catch(Exception e)
              {
                     e.printStackTrace();
               }
          }
}

Chained Exceptions in Java Example

In the above example, the main () method invokes method A ().The method A () invokes method B () which throws an exception. This exception is caught in the catch block in themethod A () and is wrapped in a new exception using the statement,

throw new Exception("Exception thrown in method A",e);

This new exception is again thrown and caught in the ca tch block in the main () method. From the output, you can see that the new exception thrown from method A () is displayed first followed by the original exception thrown from method B ( )