Monday, August 2, 2021

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

As the release of JDK 7 approaching General Availability (GA) on 2011/07/28, I thought to have a gorftlook on language enhancement as part of project coin, also called as Small language enhancements or JSR 334. Though there are 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 a diamond operator, automatic resource management using  try with resource feature, and ability to catch multiple Exception in the 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 compile your code with source 1.7. 


This article also shows you how to use JDK 7 multiple catch block with an example. I also recommend book Java 7 Recipes: A Problem-Solution Approach to learning more about all the changes made in JDK 1.7 and how to make effective use of them.g




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 some code to run on these two blocks, then either you need to use finally block or just duplicate the code on two catch blocks. 



The finally block is not an ideal solution because it will execute even if an Exception is not thrown so ultimately a lot of duplicate code which sometimes makes code unreadable and clumsy. Now with JDK7 multi catch block, we can catch multiple exceptions in one catch block separated by a 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 the above code example or JDK7 multi-catch block, we have used multiple catch blocks of JDK 1.7 and control will come on this block whenever code throws either NumberFormatException or IllegalArgumentException.


Java multiple catches 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 we will verify that by entering an input which will result in both types of Exceptions one by one. If we are able to catch both Exceptions then it's proven.

Testing of JDK 1.7 multi-cache block  

If we will enter any number with alphabets, then 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 a number with more than 5 digits 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 the 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 the source as 1.7 because this new language feature is only available in JDK7. In the next series of this JDK7 feature article, we will see how to use String in the Switch statement.


18 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.

Unknown 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.

Unknown 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

Anshudeep said...

To Add one more point –
While joining multiple statement using | make sure that you go from subtype exception class to parent exception classes. Doing something like this will result in compiler error.

// This will give compiler error
catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException ex){
ex.printStackTrace();
}

vishal singh said...

@Ashudeep while joining multiple exceptions we need to ensure that exceptions are disjoint ie there is no parent-child relationship b/w them.The example give by you...even if you reverse the order .....it will give compilation error because if you want to execute a particular catch block...lets say on Arithmetic exception...even if u only specify Exception the same block will be executed.

Baji said...

The above sample code can't compile due to "The exception NumberFormatException is already caught by the alternative IllegalArgumentException" error.

Because NumberFormatException is sub-type of IllegalArgumentException.

I was curies to know how the sample ouput was got for the author of the above example?

rama krishna said...

I even got the same error, please correct the program

Post a Comment