Tuesday April 18, 2006
What's inside InvocationTargetException? Not just Exception
Any Throwable can be wrapped inside java.lang.reflect.InvocationTargetException, as you can see from this constructor:
InvocationTargetException(Throwable target)
Even more surprisingly, a null may be inside. This is the javadoc for getCause():
Returns the the cause of this exception (the thrown target exception,
which may be null).
So when you call InvocationTargetException.getCause(), you really need to expect 4 types of causes:
try {
helloMethod.invoke(foo);
} catch (IllegalAccessException ex) {
logger.log(Level.SEVERE, "Invocation failed.", ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if(cause == null) {
throw new IllegalStateException(
"Got InvocationTargetException, but the cause is null.", ex);
} else if(cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if(cause instanceof Exception) {
logger.log(Level.SEVERE, "Invocation failed with cause: ", cause);
} else {
logger.log(Level.SEVERE, "Invocation failed with error: ", cause);
}
}
Therefore, the following may cause NullPointerException, at least in theory, though I haven't seen many people check for null:
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
cause.printStackTrace();
The following may cause ClassCastException when casting cause to RuntimeException, since cause can be of type Error.
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if(cause instanceof MyApplicationException) {
//handle it
} else {
//others are not application exception, and throw them out
throw (RuntimeException) cause;
}
}
technorati tags: InvocationTargetException, java
Posted at 09:27AM Apr 18, 2006 by chengfang in Glassfish | Comments[0]