InvocationTargetException: Unwrapping Thrown Exceptions
What you'll learn: How to properly handle exceptions thrown by methods you invoke reflectively using Method.invoke().
When you call a method using reflection's invoke(), any exception thrown by that method itself doesn't come out directly. Instead, Java wraps it inside an InvocationTargetException. Think of it like a package: the delivery truck (reflection) puts the actual error (the original exception) inside a shipping box (InvocationTargetException) before handing it to you.
Why the Wrapper?
Reflection needs to distinguish between problems calling the method (wrong arguments, access issues) and problems inside the method (business logic errors). The wrapper makes this clear: if you catch InvocationTargetException, you know the method ran but threw something.
Unwrapping with getCause()
To get the actual exception that your invoked method threw, call getCause() on the InvocationTargetException:
Method method = MyClass.class.getMethod("divide", int.class, int.class);
Object instance = new MyClass();
try {
method.invoke(instance, 10, 0); // divide by zero!
} catch (InvocationTargetException e) {
Throwable actualException = e.getCause();
System.out.println("Method threw: " + actualException.getClass().getName());
// actualException is the ArithmeticException from divide()
}
The getCause() method returns the original Throwable that was wrapped. You can then check its type, log it, or rethrow it as needed.
Practical Pattern
Always catch InvocationTargetException separately when using invoke(). This lets you handle the actual business logic exceptions differently from reflection-specific problems like IllegalAccessException or IllegalArgumentException.
Key Takeaway: When Method.invoke() throws InvocationTargetException, use getCause() to retrieve the original exception thrown by the invoked method—this unwraps the reflective layer to reveal the actual error.