Java 7 new Exception Handling using multi-catch

 

Good to hear that in Java 7 has packed with lot of new features and additional features in Exception Handling, Switch case, Collections etc., Today we will discuss about the additional features which we have got from JAVA 7 in Exception handling. 

      Lot of programmers will use single catch() block for handling all exception types by placing the common Exception as like below in Java 6 and earlier versions. 



public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (Exception e) {
   // Log the exception 
  }
 }
}



      By handling exceptions like above we may lead to lot of issues like handling exceptions efficiently and also its not good practice until Java 6. So in earlier version we used to have multiple catch statements to handle each and every exceptions which may occur in the block as like below. 





public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (NullPointerException ex) {
   // Log the exception 
  }catch (ClassCastException ex) {
   // Log the exception
  }catch (StackOverflowError err) {
   // Log the error message
  }catch (Exception e) {
   // Log the exception
  }
 }
}


       
      Buy using like this also code goes ugly and lot of huddles in handling each and every Exceptions independently in separate catch blocks. 

     To over come this issue in Java 7 have packed with multi-catch feature in Exception handling and it will be handy to use in a single catch or multiple catch as programmers wish. Lets see small example as how to use multi-catch in Java 7 



public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (NullPointerException | ClassCastException | StackOverflowError ex) {
   // Log the exception 
  }
 }
}



Hope you are clear and happy that Java 7 has given a good feature for programmers to handle exceptions in a new way. Lets discuss more new features added in Java 7 in our next tutorial. 





No comments:
Write comments