Search code examples
javaexceptioninvocationtargetexception

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?


Solution

  • 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.
        }
    }