Search code examples
javasystem.reflectioninvocationtargetexception

understanding Invocation Target Exception wrapping in Java


m is a method and I want to invoke it on a specific Instance through reflection. the following code show how I did the invokation:

try {
    m.invoke(classInstance);                
} catch (OOPAssertionError e) {

} catch (Exception e) {
    system.out(e.getCause().getClass().getName());
}

Now the Instance suppose to throw the following class when I invoke the specific method I just tried to invoke earlier, which is m in the previous code:

public class OOPAssertionError extends AssertionError {
}

I thought that the program will catch OOPAssertionError but actually it catch Exception instead . and prints the following line : "package.OOPAssertionError".

why is that happening ?


Solution

  • InvocationTargetException wraps your method's exceptions, like was written in javadoc.

    See What could cause java.lang.reflect.InvocationTargetException? for more details.

    Good luck in reflections! ;)