BackendBench
Coffee

Home โ€บ Java exceptions โ€บ InvocationTargetException

Checked exception ยท java.lang.reflect

InvocationTargetException: causes and fixes

A method invoked through reflection threw an exception; the real error is the cause.

What it looks like

java.lang.reflect.InvocationTargetException
Caused by: java.lang.IllegalArgumentException: invalid id

Extends ReflectiveOperationException in java.lang.reflect.

What it means

When code calls a method with Method.invoke (or a framework does, to run your controller, listener or test), any exception thrown by the target method is wrapped in InvocationTargetException. The wrapper has no message of its own; the useful information is in getTargetException() or getCause(). Many frameworks unwrap it for you, but when you see it in a log, skip to the Caused by line.

Common causes

How to fix it

  1. Read the nested cause and fix that exception.
  2. In your reflection code, catch InvocationTargetException and rethrow e.getCause().
  3. Prefer method handles or interfaces to reflection when you can.
  4. Log the full chain so the root cause is not hidden.

Broken and fixed

fails
try { m.invoke(bean); }
catch (InvocationTargetException e) { throw new RuntimeException(e); } // wrapper hides intent
works
try { m.invoke(bean); }
catch (InvocationTargetException e) {
    throw e.getCause() instanceof RuntimeException re ? re : new RuntimeException(e.getCause());
}

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

Spring wraps startup failures from @PostConstruct methods the same way; the bean creation error lists the real cause at the bottom.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is InvocationTargetException a checked or unchecked exception?

InvocationTargetException is a checked exception (it extends ReflectiveOperationException), so the compiler forces you to catch it or declare it with throws.

Which package is InvocationTargetException in?

It lives in java.lang.reflect, so the import is import java.lang.reflect.InvocationTargetException;.

What is the first thing to check when I see InvocationTargetException?

Read the message and the first stack trace line in your own code. The usual causes are: The target method threw any exception, checked or unchecked; and A framework invoking lifecycle callbacks (@PostConstruct, @EventListener, JUnit test methods).

Related exceptions

More tools you might need