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 the single catch block is not possible, but we can achieve this using multiple catch block where each catch block used to catch the 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.

 // 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 the single catch block
Handling multiple exceptions example in Java 7
Java 7 has introduced single catch block for handling multiple exceptions thus reduce code of catch blocks
Below example

   // 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

Similar Posts