I’m happy to announce that an other improvement from the Project Coin has be marked for inclusion in Java 7 : Improved Exception Handling for Java, from Neal Gafter. This has been announced by Joe Darcy on his blog.
This improvement add two litlte improvements to exception handling :
- Multicatch : You’ll now be able to catch multi exceptions type in one catch block
- Final Rethow : Allows you to catch an exception type and it’s subtype and rethrow it without having to add a throws clause to the method signature.
Often, we have that kind of code :
1 |
} catch (FirstException ex) { |
4 |
} catch (SecondException ex) { |
But that code is heavy for nothing really interesting. A solution is to find a common supertype of these two exceptions type and catch just that type and rethrow it. But that can catch more exceptions than you want.
So now, with that new feature, you can do :
1 |
} catch (FirstException | SecondException ex) { |
A lot more cleaner, isn’t it ?
And the second improvement is a little more complicated. Imagine that you want to catch all exceptions, make several operations and then rethrow it. The code isn’t hard to make, but the big problem is that you must add a throws clause to your method signature to manage the new exception launched by your code and this is not the objective. Now, you can do that without adding an exception throws clause :
3 |
} catch ( final Throwable ex) { |
Using the final keyword it allows you to throw an exception of the exact dynamic type that will be throwed. So if an IOException occurs, an IOException will be throwed. Of course, you have to declare the exceptions not caught. You throws clauses will exactly the same if you use the code (in //some code) without catching anything but now you can do something if that happens.
I think multi-catch is a great feature, but for me the final rethrow is not often useful for programmers and perhaps a little weird using the final keyword.
zz address: http://www.baptiste-wicht.com/2010/05/better-exception-handling-in-java-7-multicatch-and-final-rethrow/