Java 7: Catching and handling multiple Exceptions
If you write networking or IO oriented programs using Java, there will be several situations where the code on the server will catch multiple exceptions. Most of the times the exceptions are logged, sometimes they are logged and re-thrown.
Here is a snippet representing such a scenario:
One alternative would be use a more generic catch clause. For example:
With this approach the specificity of the Exception is lost, hence error handling cannot be specific, if needed. And the first approach clearly results in duplication of code.
Java 7 provides a new feature where the duplication while handling multiple exceptions can be eliminated, without using a broad catch clause. Here is how it is done in Java 7:
Important note: when used in the above manner the compiler automatically makes the generic exception variable e as final. And as per the Java documentation, even at bytecode level, the new multiple exception handling approach is more optimal.