Reputation: 28555
I recently asked another question pertaining to avoid having to use boilerplate exceptions when they are not needed (or more specifically the error being handled is not needed because the application simply cannot survive if the error is called in the first place). I've decided to swing in favor of unchecked errors in a majority of circumstances, mostly for the ease of readability. In other situations, I seem to have no choice but to use large, ugly try catch blocks.
For example in one situation I am using apache commons BeanUtilities class MethodUtils in order to use introspection to call a method in an Object of a type that is unknown. In this situation, seeing as how I am using a class that I have no control over. Am I forced to go along with the checked exception philosophy and catch 3 different exceptions each time I use the method? Or is there a way around this?
SQL sql = null;
try {
sql = (SQL) MethodUtils.invokeExactMethod(bean, "getSQL", (Object[])null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Upvotes: 0
Views: 82
Reputation: 6358
Besides Mersenne's answer, you can simply use the common base class of these exceptions in your catch block:
SQL sql = null;
try {
sql = (SQL) MethodUtils.invokeExactMethod(bean, "getSQL", (Object[])null);
} catch (Exception e) {
e.printStackTrace();
}
This will catch all three exceptions. If you're not planning to perform any specific measures on the different exceptions, this is an appropriate solution. And it works with all JDK versions.
Upvotes: 0
Reputation: 2208
Complex catch
readability is very common problem. In Java 7 it could be in more readable form:
SQL sql = null;
try {
sql = (SQL) MethodUtils.invokeExactMethod(bean, "getSQL", (Object[])null);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
Upvotes: 2