How to resolve java.lang.reflect.InvocationTargetException error

When a method of a class, invoked by Method.invoke(), throws an exception, it is wrapped by the java.lang.reflect.InvocationTargetException class.

Resolving the exception

Since the InvocationTargetException is caused by another exception thrown by the invoked method, the underlying exception can be found using the getCause() method. Therefore, resolving the InvocationTargetException error equates to finding the actual exception and resolving it.

svg viewer

Code

The code below intentionally generates an exception by dividing 1010 over 00 in the method foo() which​ is invoked using Method.invoke(). As an output, ​the InvocationTargetException, as well as the underlying exception, is displayed on the console.

import java.lang.reflect.Method;
public class ExceptionDemo {
public static void main(String[] args) {
TargetInvocation ti = new TargetInvocation();
// Get all methods of TargetInvocationClass:
Method[] m = TargetInvocation.class.getMethods();
try {
// Invoke the first method of the class:
m[0].invoke(ti);
}
catch(Exception e) {
// Print the wrapper exception:
System.out.println("Wrapper exception: " + e);
// Print the 'actual' exception:
System.out.println("Underlying exception: " + e.getCause());
}
}
}
class TargetInvocation{
public void foo() {
// Dividing by zero to intentionally throw an exception:
System.out.println(10 / 0);
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved