Home » InvocationTargetException

InvocationTargetException

by Online Tutorials Library

InvocationTargetException

The InvocationTargetException is a checked exception that holds an exception thrown by an invoked method or constructor. Since JDK 1.4, this exception has been retrofitted to conform to the general-purpose exception-chaining mechanism. The “target exception” that is provided at construction time and accessed via the getTargetException() method is now known as the cause and may be accessed via the Throwable.getCause() method, as well as the “legacy method.”

In a nutshell, when we invoke a class using the Method.invoke(), it throws an exception; it is wrapped by the java.lang.reflect.InvocationTargetException class.

Cause of InvokationTargetException

The InvokationTargetException mainly occurs while working with the Java Reflection API and try to invoke a method or constructor in the reflection layer that throws an underlying exception itself.

The reflection layer holds the actual exception thrown by the default methods.

How to Resolve java.lang.reflect.InvocationTargetException

The InvocationTargetException is caused by the invoked method, which throws an exception. The underlying exception can be found using the getCause() method. Therefore, it is necessary to find the actual exception and resolve it to resolve the InvocationTargetException.

InvocationTargetException

Consider the below example, which intentionally generating an exception (divide by zero) in the method Demo(), which is invoked using the Method.invoke(). Thus, the output will throw both the AirthmeticException (DividebyZero) and InvokationTargetException.

TestInvokationException.java:

Output:

Wrapper exception: java.lang.reflect.InvocationTargetException  Underlying exception: java.lang.ArithmeticException: / by zero  

Next TopicJava Pass by Value

You may also like