How does one re-throw the target exception of an InvocationTargetException. I have a method which uses reflection to call the invoke() method within one of my classes. However, if there is an Exception thrown within my code, I am not concerned about the InvocationTargetException and only want the target exception. Here is an example:
public static Object executeViewComponent(String name, Component c,
HttpServletRequest request) throws Exception {
try {
return c.getClass()
.getMethod(c.getMetaData().getMethod(), HttpServletRequest.class)
.invoke(c, request);
} catch (InvocationTargetException e) {
// throw the target exception here
}
}
The primary problem I am facing is that calling throw e.getCause(); doesn't throw an Exception but rather throws a Throwable. Perhaps I am approaching this incorrectly?
Since the InvocationTargetException is caused by another exception thrown by the invoked method, the underlying exception can be found using the getCause() method. Therefore, resolving the InvocationTargetException error equates to finding the actual exception and resolving it.
What Causes InvocationTargetException. The InvocationTargetException occurs mainly when working with the Java reflection API to invoke a method or constructor, which throws an exception.
The InvocationTargetException is caused by the invoked method, which throws an exception. The underlying exception can be found using the getCause() method. Therefore, it is necessary to find the actual exception and resolve it to resolve the InvocationTargetException.
InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism.
catch (InvocationTargetException e) {
if (e.getCause() instanceof Exception) {
throw (Exception) e.getCause();
}
else {
// decide what you want to do. The cause is probably an error, or it's null.
}
}
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