Before we introduced the latest feature updates and code examples from Java 7, today we look at the enhancements to Java 7 exception handling. Another minor language enhancement from the coin project has been included in Java 7: the Java Enhanced exception handling feature proposed by Google's full-time engineer and Java lecturer, Neal Gafter. Joe Darcy, the leader of Open JDK development, has announced the change on his blog.
This change adds two minor enhancements to the exception handling mechanism:
Multicatch: Developers can now capture multiple exception types in a catch code block;
Final Rethrow: It allows the developer to capture an exception type and its subtypes, and it can be thrown back without adding a throw clause to the method declaration.
In the past, when we captured multiple exception types, we often used the following types of code:
} catch (FirstException ex)
{
logger.error(ex);
throw ex;
} catch(SecondException ex)
{
logger.error(ex);
throw ex; }
But the above code has no advantage but long. One workaround is to find the common subtypes of the two exception types, and only catch and throw them. But this method usually captures some exceptions that you don't need.
Now with the help of the new features, developers can use the following code:
} catch (FirstException | SecondException ex) {
logger.error(ex);
throw ex;
}
This code looks much simpler and clearer.
The second enhancement is a bit more complex. If the developer wants to catch all of the exceptions, throw them after a few necessary actions. It's not difficult to write code, but a developer must add a throw clause to the method declaration to manage the new exception that the code emits. Now with final Rethrow, developers can accomplish this task without adding an exception-throwing clause:
try {
// some code
} catch (final Throwable ex) {
// some more code
throw ex;
}
By using the final keyword, the developer can throw the exact dynamic type exception that is required. So if a IOException exception occurs, then IOException will be thrown. Of course, developers must declare exceptions that are not caught. If the developer does not catch any exceptions in the try code block (in the//some more Code section), the throw clause is exactly the same as before, whereas if some exceptions are caught, the developer can handle it accordingly.
The Multi-Catch in Java 7 is a very good feature, but final rethrow is not commonly used by programmers.