Tuesday, May 29, 2012

Java 7: Multi-catch block


I wrote a blog about using multiple exceptions catch statement long before Java 7 was released. That time, multi-catch block and better re-throw was part of Project coin, small language enhancements. Now Java7 being out, we can see it action. This is how it works.

First of all, to get multi-catch working, we need to set '-source 7' as commond line parameter during compilation.
We can write multi-catch statement as -

        try {
            newCatchBlock.methodWithMultipleExceptions();
        } catch (MyException1 | MyException2 exception) {
            ...
        }

This can be useful in few cases and can save few lines of code. The type of exception caught will be the closest common base class. If there is no common class, the type of object will be Exception, which is the base class for all exceptions. However, that means you will not be able to invoke methods from MyExcepetion1 or MyExcepetion2, as the object will be of type Exception. The parameter in catch block is final. Trying to reassign value to it will result in error "Multi catch exception may not be assigned".

Another important point to note is that exceptions in multi-catch statement can not have parent-child relationship. You can not have catch block like (IOException | FileNotFoundException exception) as FileNotFound is subclass of IOException.

When I looked for how this feature is implemented in language, I found that there is no magic here. The generated bytecode will just have a plane old catch block which catches exception of closest common base class. That explains the type of caught exception as well.

This feature adds a bit of syntactic sugar. As I mentioned in my previous blog on this topic, I don't see this as being very useful in day to day programming. I don't remember last time when I wanted to catch multiple exceptions and have the same code to handle them. However, this does make Java a little bit better than before.