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);
}
}
Copyright ©2024 Educative, Inc. All rights reserved