Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-throw an InvocationTargetException target exception

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?

like image 844
Vincent Catalano Avatar asked Apr 18 '12 17:04

Vincent Catalano


People also ask

How do I fix InvocationTargetException in Java?

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 invocation target exception?

What Causes InvocationTargetException. The InvocationTargetException occurs mainly when working with the Java reflection API to invoke a method or constructor, which throws an exception.

How do you throw InvocationTargetException?

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.

What does InvocationTargetException mean?

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.


1 Answers

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.
    }
}
like image 83
JB Nizet Avatar answered Sep 19 '22 09:09

JB Nizet