Friday, July 22, 2011

How to use Java 1. 7 Multiple Catch Block with example - JDK 7 tutorial

As release of JDK 7 approaching General Availability (GA) on 2011/07/28, I thought to have a look on language enhancement as part of project coin, also called as Small language enhancements or JSR 334. Though there is not any major changes like Enum or Generics of Java 1.5,  but they are still very useful, in terms of simplifying your day to day programming task. Some of the interesting changes are allowing String in Switch cases, inclusion of fork join framework in JDK itself , , type inference using diamond operator, automatic resource management using  try with resource feature, and ability to catch multiple Exception in single catch block . In this Java 7 tutorial, we will learn how multi catch block of JDK 1.7 makes Exception handling code simpler and elegant. Multiple catch block will allow you to catch multiple exceptions in one block but it’s only available in JDK7 and you need to compiler your code with source 1.7. This article also shows you how to use JDK 7 multiple catch block with example. I also recommend book Java 7 Recipes: A Problem-Solution Approach to learn more about all the changes made in JDK 1.7 and how to make effective use of them.



JDK 1. 7 feature: Improved exception handling using multi-catch block

jdk7 multi-cache block example tutorialJava has always been criticized for having checked exception and polluting code with cluttered exception handling code, multi-catch block in Java 1.7  certainly assuage those wounds. With multi catch block,  you can catch multiple exceptions in one catch block, which will eventually result in more readable code. Prior to JDK 7 if you want to catch two exceptions, you need to provide two catch blocks and if you have same code to run on these two blocks, then either you need to use finally block or just duplicate the code on two catch blocks. finally block is  not an ideal solution, because it will execute even if Exception is not thrown so ultimately lot of duplicate code which sometime makes code unreadable and clumsy. Now with JDK7 multi catch block we can catch multiple exception in one catch block separated by pipe (|) and reduce the code duplication. Let’s see an example of multiple exceptions catching in Java 7.

public static void main(String args[]) {
    Scanner scnr = new Scanner(System.in);
    String number = scnr.next();
    try {
        if (number.length() > 5) {
            throw new IllegalArgumentException();
        }
        Integer.parseInt(number);

    } catch (NumberFormatException | IllegalArgumentException e) {
        e.printStackTrace();
    }
}
In above code example or JDK7 multi-catch block we have used multiple catch block of JDK 1.7 and control will come on this block whenever code throws either NumberFormatException or IllegalArgumentException.


Java 7  multiple catch block example tutorial

We have seen code making use of this new Java 7 feature of catching more than one Exception in one catch block. In our example, we are catching NumberFormatException and IllegalArgumentException together and her we will verify that by entering input which will result in both type of Exception one by one. If we are able to catch both Exception than it's proven.

Testing of JDK 1.7 multi-cache block  

If we will enter any number with alphabets, than it will throw NumberFormatException as shown below :

Input: 23ff
java.lang.NumberFormatException: For input string: "23ff"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:492)
        at java.lang.Integer.parseInt(Integer.java:527)
        at jdk7demo.JDK7Demo.main(JDK7Demo.java:25)


Now let's enter number with more than 5 digit this will result in IllegalArgumentException as per our code.
Input :123333
java.lang.IllegalArgumentException
        at jdk7demo.JDK7Demo.main(JDK7Demo.java:23)
      
I used Netbeans 7 to compile and run this project. Setting up JDK 7 in Netbeans is very easy just download JDK7 and then click on Tool-->Java Platform and then click "Add Platforms" it will open a file browser just point out JDK7 installation directory and it will import JDK 1.7  binaries , source and docs and set it up for your use. One more thing you need to remember is that setting source as 1.7 because this new language feature is only available in JDK7. In next series of this JDK7 feature article we will see how to use String in Switch statement.


Recommended Book for further Reading
Java 7 Recipes: A Problem-Solution Approach By Josh Juneau, Carl Dea, Freddy Guime, John O'Conner



14 comments :

Anonymous said...

I agree with you multi-cache block has improved exception handling and made code more cleaner. JDK7 project coin is worth of money.

Anonymous said...

"Multi-CACHE" block, eh dude? Brilliant.

Ujwol Shrestha said...

Nice read..But please correct..it is not "Multi-Cache" ..it is "Multi-Catch"

Javin @ transient vs volatile said...

Thanks Ujwol for pointing that its indeed meant to catch multiple Exceptions in Java and that's why called multi-catch in common language.

Subrat said...

how to provide different implementation for different type exception.
eg.
try{}
catch(IOException |FileNotFoundException| AWTException ex)
in the above code if we want to provide different handle each exception, how can we handle that with one exception instance ex?
Can you please provide the solution with example?

About me said...

@Subrat just use multiple catch statements like before. The new functionality is only there if you want to do much the same thing in every case.

amit inamdar said...

But in the code NumberFormatException and IllegalArguementException gives error... at the compile time.....

Javin @ 32-bit vs 64-bit JVM said...

Hi Amit, have you set Java source level to 1.7 as this functionality is only present in Java 1.7? If you are using Eclipse, it's worth to check compiler settings. You can also post your code and some more details, and I will try to help you out.

Anonymous said...

This blog entry is 2 years old and STILL you haven't corrected your use of "CACHE" to "CATCH".
What does that say about your attention to detail at work? I'm glad you're not one of my coders.

Javin @ Parse String to int in Java said...

@Anonymous, Welcome to Javarevisited. Thanks for pointing that out, some how that missed correcting that to catch. Glad to see your attention of detail :).

Anonymous said...

As said, this post is more than 2 years old but isn't worth of mentioning that: NumberFormatException is a subclass of IllegalArgumentException and the compiler issues an error related to multi-catch statement using the subclassing? I think the author must replace just the code not his or her comments.

gundamaiah annamaina said...

I am trying to do the above program but i am getting compile time error "The exception NumberFormatException is already caught by the alternative exception IllegalArgumentException".Please help me how to resolve this

viveksoundararajan said...

It gives error... at the compile time.....

Javin said...

Hello @vivek, what error you get, can you please post it here

Post a Comment