Thursday, 30 May 2013

Java 7 feature :Multi catch block exception handling example with tutorial

Java 7 features – Exception Handling

Java 7 language has introduced features like Usage of Stirings in Switch case, and improving the exception
handling . It introduced multi catch block

Prior to java 7, if we want to handle multiple exceptions in single catch block is not possible, but we can achieve this using multiple catch block where each catch block used to catch single exception.
Let us see the example of multi catch exception handling in java 7

Handling multiple exceptions in catch block example prior 7

For example, prior to java 7, if we want to catch multiple exceptions, thrown by try block, we need to write a separate catch block for each exception type as shown below.
 
try{
 // possible code throwing exception 
     }catch(IllegalArgumentException iae){
 //catch  IllegalArgumentException and print error message
     }catch(Exception iae){
 //catch  Exception and prints error message
     }
Java 7 introduced multiple exceptions are handled in single catch block
Handling multiple exceptions example in java 7
Java 7 has introduced single cach block for handling multiple exceptions thus reduce code of catch blocks
Below example
try{
   // possible code throwing exception
}
catch(IllegalArgumentException iae|Exception e) {
}
In the above code, IllegalArgumentException and Exceptions are defined in same catch block with separator pipe | symbol

Advantages of Multi catch exceptions in Single catch block:-

1. Simplify the coding
2. Decrease code duplicate
3. Reduces catch blocks


That’s my understanding on multi catch block in java 7 language

0 comments:

Post a Comment