CKTIS / Java
InvocationTargetException — wrapping a failure in invoked code
InvocationTargetException wraps an exception thrown by a reflectively invoked method or constructor. Read getCause() to identify the original problem instead of diagnosing only the wrapper exception.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
try {
method.invoke(receiver, args);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
}InvocationTargetException, in java.lang.reflect, is a checked exception extending ReflectiveOperationException. It wraps an exception thrown by a reflectively invoked method or constructor. The wrapper itself therefore does not imply that the reflection mechanism failed.
With Method.invoke(), distinguish a failure in the invoked code from invocation problems: insufficient access can produce IllegalAccessException, while incompatible arguments produce IllegalArgumentException. If the method itself throws IllegalArgumentException, however, you receive InvocationTargetException with that exception as its cause. Wrapping also occurs when the method throws an unchecked exception.
Prefer getCause() to retrieve the cause; the older getTargetException() exposes the same information. The API permits a null cause, so account for it in general diagnostic utilities. Do not discard the cause when propagating a failure. In the example, method.invoke(null) invokes the static method fail(), and the catch block displays the wrapper and original exception separately.
Examples
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void fail() {
throw new IllegalStateException("demo failure");
}
public static void main(String[] args) throws ReflectiveOperationException {
var method = Main.class.getMethod("fail");
try {
method.invoke(null);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
System.out.println(e.getClass().getSimpleName());
System.out.println(cause.getClass().getSimpleName() + ": " + cause.getMessage());
}
}
}Result
InvocationTargetException IllegalStateException: demo failure
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.