Consider the following Java code:
try{
// do something
// this piece of code throws several checked exceptions.
} catch (IllegalArgumentException e) {
handleException(e);
} catch (IllegalAccessException e) {
handleException(e);
} catch (InvocationTargetException e) {
handleException(e);
} catch (InstantiationException e) {
handleException(e);
} catch (NoSuchMethodException e) {
handleException(e);
} catch (IOException e) {
handleException(e);
} catch (NoSuchFieldException e) {
handleException(e);
}
The code in try
block throws several checked exceptions. All I want to do is to log a message when an exception occurs (with some custom message strings). I.e. my exception handling logic is same for all exceptions.
I feel the above code dosn't look good (more LOC and reduced readability).
Is there any better ways to handle such cases?
The following solution is not a best practice, so not recommended (by Check style).
try{
// do something very bad
} catch (Exception e) {
handleException(e);
}
Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block.
If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.
In Java 6 you don't have any option much more appealing than what you have already suggested.
But Java 7 has a multi-catch statement that you can use:
catch(IllegalArgumentException | IllegalAccessException | IOException exception) {
handleException(e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With