Catch multiple exceptions and rethrow exception in java

Let’s learn catch multiple exceptions and rethrow exception in java.

Catch multiple exceptions and rethrow exception in java

Before java 7 a programmer would catch multiple exceptions one by one like this,

try
{
   // code that throw exceptions 1 and 3
}
catch(SQLException e)
{
   logger.log(e);
}
catch(IOException e)
{
   logger.log(e);
}
catch(Exception e)
{
   logger.severe(e);
}

As you can see there are two exceptions IOException and SQLException which has same statements. Even though we are writing two catch blocks.

java catch multiple exceptions and rethrow exception

In Java 7 catch block is upgraded. We can combine two catch blocks into one using multi catch syntax.

try
{
   // code that throw exceptions 1 and 3
}
catch(SQLException | IOException e)
{
   logger.log(e);
}
catch(Exception e)
{
   logger.severe(e);
}

We use multiple catch block when a java program execute various tasks at the instance of different exceptions.

NOTE:

  • Use multiple “catch” blocks for catching multiple exceptions and having similar code. Hence reducing code duplication.
  • Multiple exceptions are separated using pipe (|).
  • Byte code generated by this attribute is small hence reduce code redundancy.

Rethrow exception

In rethrow statement, particular exception caught can be rethrown in the “catch” block.

Suppose in a java program if you are catching an exception and want that exception be known to the caller method, in that case rethrow exception is used.

NOTE: only checked exceptions can be rethrown.

Let’s see an example.

public class RethrowException
{
   public static void main(String[] args)
   {
      try
      {
         divideByZero();
      }
      catch(ArithmeticException ae)
      {
         System.out.println("Rethrown exception in main() method");
         System.out.println(ae);
      }
   }
   static void divideByZero()
   {
      int a, b, div;
      try
      {
         a = 8 ;
         b = 0 ;
         div = a / b ;
         System.out.println(a + "/" + b + " = " + div);
      }
      catch(ArithmeticException ae)
      {
         System.out.println("Exception caught!!! cannot divide by zero");
         throw ae; // rethrows exception
      }
   }
}

Output:

Exception caught!!! cannot divide by zero
Rethrown exception in main() method
java.lang.ArithmeticException: / by zero


Also read – Strings in java