by Dinesh Thakur Category: Exception Handling

There might be situations in your program where you want to both catch an exception in your code and also want its caller be notified about the exception. This is possible by rethrowing the exception using throw statement.

The following program demonstrates how an exception is rethrown using the throw statement.

public class RethrowingExceptions

{
         static void divide()
    {
        int x,y,z;
        try
        {
           x = 6 ;
           y = 0 ;
           z = x/y ;
           System.out.println(x + "/"+ y +" = " + z);
         }
         catch(ArithmeticException e)
         {
          System.out.println("Exception Caught in Divide()");
          System.out.println("Cannot Divide by Zero in Integer Division");
          throw e; // Rethrows an exception
         }
     }
      public static void main(String[] args)
     {
             System.out.println("Start of main()");
             try
            {
                 divide();
             }
             catch(ArithmeticException e)
            {
                System.out.println("Rethrown Exception Caught in Main()");
                System.out.println(e);
            }
      }
 }

Rethrowing Exceptions Java Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular 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.



Search Content