Catching Multiple Exceptions in Java 7

Catching Multiple Exceptions in Java 7 is a very good change Oracle had made in Exception Handling to avoid duplication of code.

Catching Multiple Exceptions in Java 7

Java 7 has introduced multi catch functionality in a single catch block to avoid redundancy of catching multiple exception that have same action associated to them. For Java 6 and earlier we used to repeat action in catch block for every exception though action is same for multiple exceptions.

Here whenever we have FileNotFoundException and NumberFormatException, those are indications of having something wrong with the input and hence we have to send mail to functional team to inform about it.

In other cases like NullPointerException and ArrayIndexOutofBoundsException, we have to inform technical team to take action on the issue. Here we are performing same action for two different exceptions, making code redundant.

Catching Multiple Exceptions

From Java 7 we can catch multiple exceptions in single catch block. Exceptions have to separated by | (pipe) symbol. With Java 7 above code, can be refactored to:

As shown above we are catching technical exceptions NullPointerException and ArrayIndexOutofBoundsException in a single catch block to send mail to technical team and FileNotFoundException and NumberFormatException in one catch block to send mail to functional team. This will avoid writing redundant code and to maintain clean code.

The exception object in catch block having multiple exceptions is always final. You can’t modify values of the variable within catch block. If you want to do so, you can throw it and later catch, check the type of exception object and can modify it.

You cannot catch both parent and child class exceptions in single catch block like FileNotFoundException and IOException because The exception FileNotFoundException is already caught by the alternative IOException.

Bytecode generated for Catching Multiple Exceptions in Single catch block will be smaller as it reduces the redundancy of both exception handlers and duplication

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates.