Labels

Blog Archive

Saturday, 28 December 2013

Java7 – More precise Re-throw of an Exception

In this tutorial we are going to see re-throw exception in Java7.
In previous versions of Java re-throwing exception in catch block didn’t indicate the actual exceptions possible from the try block.Also you could not change the type of exception thrown in the catch block without changing the method signature.
Now in Java7,  the semantics for catching and throwing exceptions has been redefined.If you catch an exception of some type, and don’t assign the exception variable, the complier will copy over the checked exception type that can be thrown from try block.
Old way to Re-throw 
 public static void main(String[] args) throws IOException,SQLException {
  // TODO Auto-generated method stub
  
  
   try {
    readFileSaveInDatabase();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    System.err.println(e.getMessage());
    throw e;
   }catch (IOException  e) {
    // TODO: handle exception
    System.err.println(e.getMessage());
    throw e;
   }
}
   
Consider the above code in that we are throwing IOException and SQLException. In that we are logging each type of exception being thrown by try block before re-throwing them.So there is duplication of code in catch block.So before Java to avoid the code duplication we can write the code as follows

 public static void main(String[] args) throws Exception{
  // TODO Auto-generated method stub
  
  
   try {
    readFileSaveInDatabase();
   } catch (Exception e) {
    // TODO Auto-generated catch block
    System.err.println(e.getMessage());
    throw e;
   }
   
  

 }

But, in above code we require to re throw the exception of type java.lang.Exception from the calling method

Java7 Re-throw

public static void main(String[] args) throws IOException,SQLException {
  // TODO Auto-generated method stub
  
  
   try {
    readFileSaveInDatabase();
   } catch (final Exception e) {
    // TODO Auto-generated catch block
    System.err.println(e.getMessage());
    throw e;
   }
   
  

 }

In above code the keyword final is used in catch clause. When a parameter is declared final, the Java complier statically knows  to only throw those checked exception that were thrown by try block and were not caught in any preceding catch blocks.

0 comments

Post a Comment