You are here:   HomeJava ProgrammingException HandlingChained Exceptions in Java Example
by Dinesh Thakur Category: Exception Handling

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





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular