This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

* to ask: what can lead to Java. Lang. Reflect. InvocationTargetException? *

I tried to understand and read what might be causing it, but I couldn’t understand that there was this place in my code:

 try{.. m.invoke(testObject); . }catch(AssertionError e){
 ...
 } catch(Exception e){
 ..
 }
Copy the code

The fact is that when it attempts to invoke a method, it throws InvocationTargetException rather than other expected exception (especially ArrayIndexOutOfBoundsException). Because I actually know that call what method, so I go directly to the method code, and should be thrown line adds a try-catch block ArrayIndexOutOfBoundsException, Thrown it ArrayIndexOutOfBoundsException indeed as expected. However, when it rises, it will change in some way as InvocationTargetException, And catch in the above code (Exception e) e is InvocationTargetException ArrayIndexOutOfBoundsException rather than expected.

What causes this behavior? How do I check?

Answer 1: By using reflection to call methods, you have added an additional level of abstraction. Reflector to pack any abnormalities in InvocationTargetException, the exception allows you to discern the reflection call fails (for example, your argument list is invalid) method is called by the actual result in abnormal and the distinction between failures.

Only in InvocationTargetException reason, can find the original cause.

Answer 2:

This exception will be thrown if:

InvocationTargetException based method - if an exception is thrown.Copy the code

So, if you use the reflection API calls the method throws an exception (for example, a runtime exception), the reflection API will exception to InvocationTargetException.

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