What could cause java.lang.reflect.InvocationTargetException?


Well, I've tried to understand and read what could cause it but I just can't get it:

I have this somewhere in my code:

 } catch(AssertionError e){
 } catch(Exception e){

Thing is that, when it tries to invoke some method it throws InvocationTargetException instead of some other expected exception (specifically ArrayIndexOutOfBoundsException). As I actually know what method is invoked I went straight to this method code and added a try-catch block for the line that suppose to throw ArrayIndexOutOfBoundsException and it really threw ArrayIndexOutOfBoundsException as expected. Yet when going up it somehow changes to InvocationTargetException and in the code above catch(Exception e) e is InvocationTargetException and not ArrayIndexOutOfBoundsException as expected.

What could cause such a behavior or how can I check such a thing?

7/27/2018 12:53:06 PM

Accepted Answer

You've added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException, which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn't valid, for example) and a failure within the method called.

Just unwrap the cause within the InvocationTargetException and you'll get to the original one.

4/10/2015 10:13:31 AM

The exception is thrown if

InvocationTargetException - if the underlying method throws an exception.

So if the method, that has been invoked with reflection API, throws an exception (runtime exception for example), the reflection API will wrap the exception into an InvocationTargetException.


Use the getCause() method on the InvocationTargetException to retrieve the original exception.


From the Javadoc of Method.invoke()

Throws: InvocationTargetException - if the underlying method throws an exception.

This exception is thrown if the method called threw an exception.


That InvocationTargetException is probably wrapping up your ArrayIndexOutOfBoundsException. There is no telling upfront when using reflection what that method can throw -- so rather than using a throws Exception approach, all the exceptions are being caught and wrapped up in InvocationTargetException.


This will print the exact line of code in the specific method, which when invoked, raised the exception:

try {

    // try code

} catch (InvocationTargetException e) {

    // Answer:
} catch (Exception e) {

    // generic exception handling