What Causes java.lang.reflect.InvocationTargetException?
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses — Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.
Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.
The feedback is available from the minute you are writing it.
Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.
Of course, Digma is free for developers.
30% less RAM and a 30% smaller base image for running a Spring Boot application? Yes, please.
Alpaquita Linux was designed to efficiently run containerized Java applications.
It’s meant to handle heavy workloads and do it well.
And the Alpaquita Containers incorporates Liberica JDK Lite, a Java runtime tailored to cloud-based services:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
When working with Java Reflection API, it is common to encounter java.lang.reflect.InvocationTargetException.
In this tutorial, we’ll take a look at it and how to handle it with a simple example.
2. Cause of InvocationTargetException
It mainly occurs when we work with the reflection layer and try to invoke a method or constructor that throws an underlying exception itself.
The reflection layer wraps the actual exception thrown by the method with the InvocationTargetException.
Let’s try to understand it with an example.
We’ll write a class with a method that intentionally throws an exception:
Let’s invoke the above method using reflection in a Simple JUnit 5 Test:
In the above code, we have asserted the InvocationTargetException, which is thrown while invoking the method. An important thing to note here is that the actual exception — ArithmeticException in this case — gets wrapped into an InvocationTargetException.
Now, why doesn’t reflection throw the actual exception in the first place?
The reason is that it allows us to understand whether the Exception occurred due to failure in calling the method through the reflection layer or whether it occurred within the method itself.
3. How to Handle InvocationTargetException?
Here the actual underlying exception is the cause of InvocationTargetException, so we can use Throwable.getCause() to get more information about it.
Let’s see how we can use getCause() to get the actual exception in the same example used above:
We’ve used the getCause() method on the same exception object that was thrown. And we have asserted ArithmeticException.class as the cause of the exception.
So, once we get the underlying exception, we can re-throw the same, wrap it in some custom exception or simply log the exception based on our requirement.
4. Conclusion
In this short article, we saw how the reflection layer wraps any underlying exception.
We also saw how to determine the underlying cause of the InvocationTargetException and how to handle such a scenario with a simple example.
How to Resolve InvocationTargetException in Java

If a InvocationTargetException is a checked exception in Java that wraps an exception thrown by an invoked method or constructor. The method or constructor that throws the exception is invoked using the Method.invoke() method. The InvocationTargetException is quite common when using the Java Reflection API.
The Java reflection layer wraps any exception as an InvocationTargetException . This helps clarify whether the exception is caused by an issue in the reflection call or within the called method.
What Causes InvocationTargetException
The InvocationTargetException occurs mainly when working with the Java reflection API to invoke a method or constructor, which throws an exception.
This underlying exception is the actual cause of the issue, therefore resolving the InvocationTargetException equates to finding and resolving the underlying exception that occurs within the invoked method.
InvocationTargetException Example
Here is an example of a InvocationTargetException thrown when a method that is called using Method.invoke() throws an exception:
In this example, the main() method invokes divideByZero() using Method.invoke() . Since divideByZero() throws an ArithmeticException , it is wrapped within an InvocationTargetException thrown in the main() method:
How to Resolve InvocationTargetException
Since the underlying exception is the actual cause of the InvocationTargetException , finding and resolving the underlying exception resolves the InvocationTargetException . The getCause() method of the Throwable class can be used to obtain the underlying exception. The earlier example can be updated accordingly to get the underlying exception and print its stack trace:
Running the above will print out the stack trace of the underlying ArithmeticException :
Track, Analyze and Manage Java Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today.
«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»
Исправление: Ошибка Java.lang.reflect.InvocationTargetException при использовании командный обозреватель везде 2010 SP1 для Eclipse для сохранения или просмотр рабочего элемента
На компьютере установить следующее программное обеспечение:
Eclipse 3.5 Eclipse 3.6 или продукта, который основан на одной из этих версий.
Командный обозреватель Microsoft Visual Studio везде 2010 Пакет обновления 1 (SP1) для Eclipse
Windows Internet Explorer 9
Командный обозреватель везде 2010 используйте для подключения к серверу Microsoft Team Foundation Server (TFS).
При попытке сохранить или просмотреть рабочий элемент, содержащий несколько элементов управления HTML.
В этом случае, сохранить или просмотреть завершится неудачно. Кроме того, появляется приведенное ниже сообщение об ошибке:
Причина
Эта проблема возникает из-за изменения в механизме JavaScript, появившееся в Internet Explorer 9. Изменение конфликтует вызывающего кода в уязвимых версиях Eclipse. Этот конфликт приводит к failaure функции для рабочего элемента, содержащий заполнены в командный обозреватель везде 2010 с пакетом обновления 1 элемент управления текстом в формате RTF. Таким образом сообщение об ошибке всплывает.
Решение
Сведения об исправлении
Исправление доступно для загрузки на следующий веб-узел центра загрузки корпорации Майкрософт:
загрузить исправление. Дополнительные сведения о том, как загрузить файлы поддержки Майкрософт щелкните следующий номер статьи базы знаний Майкрософт:
119591 Как загрузить файлы технической поддержки Майкрософт через веб-службы Этот файл был проверен корпорацией Майкрософт на наличие вирусов. Корпорация Майкрософт использует самые последние на момент публикации файла версии антивирусного программного обеспечения. Файл хранится на защищенных серверах, что предотвращает его несанкционированное изменение. Примечание. Чтобы установить данное исправление, выполните следующие действия.
Сохраните файл Tfseclipseplugin-updatesitearchive-10.1.0-qfe1.zip пакета исправлений в локальной папке.
В меню Справка выберите пункт Установки нового программного обеспечения.
Нажмите кнопку Добавить.
В поле имя введите подключаемый модуль архивации локальной командный обозреватель и нажмите кнопку Архивировать.
Выберите файл Tfseclipseplugin-updatesitearchive-10.1.0-qfe1.zip, который был сохранен в локальной папке и нажмите кнопку ОК.
В диалоговом окне установки выберите установите флажок, соответствующий командный обозреватель везде в списке функций.
Два раза нажмите кнопку Далее .
Принять условия лицензионного соглашения на использование программного обеспечения корпорации Майкрософт, а затем нажмите кнопку Далее.
Нажмите кнопку Завершить.
Дополнительные сведения об установке подключаемого модуля Team Foundation Server и клиентом командной строки загрузить и просмотреть веб-страницу Майкрософт:
Предварительные условия
Для установки этого исправления необходимо иметь Microsoft Visual Studio командный обозреватель везде 2010 на компьютере установлен Пакет обновления 1 (SP1).
Необходимость перезагрузки
После установки этого исправления необходимо перезапустить Eclipse.
Сведения о замене исправлений
Это исправление не заменяет ранее выпущенные исправления.
Сведения о файлах
Глобальная версия этого исправления содержит атрибуты файла (или более поздние атрибуты файлов), приведенные в следующей таблице. Дата и время для файлов указаны в формате UTC. При просмотре сведений о файлах выполняется перевод соответствующих значений в местное время. Чтобы узнать разницу между временем UTC и местным временем, откройте вкладку Часовой пояс элемента Дата и время панели управления.
What could cause java.lang.reflect.InvocationTargetException?
Well, I’ve tried to understand and read what could cause it but I just can’t get it:
I have this somewhere in my code:
Thing is that, when it tries to invoke some method it throws InvocationTargetException instead of some other expected exception (specifically ArrayIndexOutOfBoundsException ). As I actually know what method is invoked I went straight to this method code and added a try-catch block for the line that suppose to throw ArrayIndexOutOfBoundsException and it really threw ArrayIndexOutOfBoundsException as expected. Yet when going up it somehow changes to InvocationTargetException and in the code above catch(Exception e) e is InvocationTargetException and not ArrayIndexOutOfBoundsException as expected.
What could cause such a behavior or how can I check such a thing?
15 Answers 15
You’ve added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException , which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn’t valid, for example) and a failure within the method called.
Just unwrap the cause within the InvocationTargetException and you’ll get to the original one.
To do that, you can do exception.printStackTrace() and look at the "Caused By:" section instead of the top half/normal section.
You can also catch the exception and use the getCause() method on it, which can also be re-thrown, if desired. Something like try <. >catch (InvocationTargetException ex) < log.error("oops!", ex.getCause()) >or . catch.
The exception is thrown if
InvocationTargetException — if the underlying method throws an exception.
So if the method, that has been invoked with reflection API, throws an exception (runtime exception for example), the reflection API will wrap the exception into an InvocationTargetException .
Use the getCause() method on the InvocationTargetException to retrieve the original exception.
From the Javadoc of Method.invoke()
Throws: InvocationTargetException — if the underlying method throws an exception.
This exception is thrown if the method called threw an exception.
![]()
This will print the exact line of code in the specific method, which when invoked, raised the exception:
![]()
That InvocationTargetException is probably wrapping up your ArrayIndexOutOfBoundsException . There is no telling upfront when using reflection what that method can throw — so rather than using a throws Exception approach, all the exceptions are being caught and wrapped up in InvocationTargetException .
![]()
This describes something like,
InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. As of release 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 aforementioned «legacy method.»
![]()
You can compare with the original exception Class using getCause() method like this :
I had a java.lang.reflect.InvocationTargetException error from a statement calling a logger object in an external class inside a try / catch block in my class .
Stepping through the code in the Eclipse debugger & hovering the mouse over the logger statement I saw the logger object was null (some external constants needed to be instantiated at the very top of my class ).
A problem can also be that the targetSdkVersion is upped and that you use deprecated Gradle manifest features. Try lowering the targetSdkVersion again and see if it works. In my case it was targetSdkVersion 31 -> 30
This exception is thrown if the underlying method(method called using Reflection) throws an exception.
So if the method, that has been invoked by reflection API, throws an exception (as for example runtime exception), the reflection API will wrap the exception into an InvocationTargetException.
I was facing the same problem. I used e.getCause().getCause() then I found that it was because of wrong parameters I was passing. There was nullPointerException in fetching the value of one of the parameters. Hope this will help you.
![]()
Invocation Target Exception:
I strongly believe that any naming convention has diligent thoughts invested in it. And, it is more than likely that our questions have their answers in the names, if we tried finding a rationale behind the name.
Let’s break the name up into 3 parts. "Exception" has occurred when "Invoking" a "Target" method. And, the exception is thrown with this wrapper when, a method is invoked via reflection in Java. While executing the method, there could be any type of exception raised. It is by design, that the actual cause of the exception is abstracted away, to let the end user know that the exception was one that occurred during a reflection based method access. In order to get the actual cause, it is recommended that the exception is caught and ex.getCause() is called. Best practice is to, in fact throw the cause from the catch block that caught the InvocationTargetException
I know it is similar to the other answers, but I wanted to make it more clear about "when" this exception type is generated by Java, so that it is a mystery to none.