Java catch multiple exceptions and rethrow exception

In this post we are going to learn java catch multiple exceptions and rethrow exception.

java catch multiple exceptions and rethrow exception

Java catch multiple exceptions and rethrow exception

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.

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.

Java 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 JavaRethrowDemo
{
   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 – how to rename file in java