Thursday, January 17, 2013
Java 7 Improved Exception Handling - Multiple Catch block
Java 7 in many ways improved exception handling. Two of the feature of Java 7 which improves exception handling are ability to catch 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 code and reduced readability. Java 7 some how reduces this pain by improve 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.
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 subsequent 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, its not considered as good practice. With multiple exception catch block in Java 7, you can combine handling of these two exception at one place in 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 :
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 combining two catch blocks which are essentially doing same job or just a copy paste. By using Java 7 multiple catch block, you can reduce lot of boilerplate code in Java.
Other Java 7 tutorials for Java programmer