Java 7 in many ways improved exception handling. Two of the feature of Java 7 which improves exception handling are the ability to catch the multiple exception in one catch block and closing resources automatically using Automatic resource management block. Java has long been criticized for its verbose exception handling code, mandatory to handle checked Exception in Java. Programmers always complained that it clutter the code and reduced readability. Java 7 somehow reduces this pain by improving Exception handling feature e.g. multiple catch and ARM blocks. In this Java 7 tutorial, we will see how to catch multiple exceptions in one catch block using JDK7.
How to catch multiple Exception in one catch block
One place where I feel catching multiple exceptions in one catch block helps is Java database connectivity, Java IO and formatting date in Java. Since most of JDBC code throws checked SQLException, IO related code throws IOException and date formatting throws ParseException, which can't be handle in one catch block prior to Java 7. Though there is an alternative to catch java.lang.Exception instead of java.io.IOException and subsequently checked exceptions but that approach is fragile because it will also catch unintended exceptions. Catching java.lang.Exception means your code is open for all kind of exception, it's not considered as good practice. With multiple exception catch block in Java 7, you can combine handling of these two exceptions at one place in the code.
Code before Java 7
After Java 7, both of catch block can be replaced with a simple multiple exception catch block, as shown below:
Here are some more important features from Java 7 release, you can read about them here:
The important point to note is that variable ex is final variable here and can not be reassigned. Another place where you can use this improved Exception handling feature is to combine two catch blocks which are essentially doing the same job or just a copy paste. By using Java 7 multiple catch block, you can reduce a lot of boilerplate code in Java.
Other Java 7 tutorials for Java programmer