Android method invoke invocationtargetexception

Что вызывает java.lang.reflect.Исключение InvocationTargetException?

Узнайте, что вызывает java.lang.reflect.Исключение InvocationTargetException.

Автор: baeldung
Дата записи

1. Обзор

При работе с Java Reflection API часто встречается java.lang.reflect.InvocationTargetException . В этом уроке мы рассмотрим его и то, как с ним справиться, на простом примере .

2. Причина исключения InvocationTargetException

В основном это происходит, когда мы работаем со слоем отражения и пытаемся вызвать метод или конструктор, который сам создает базовое исключение.

Слой отражения обертывает фактическое исключение, вызванное методом, с помощью исключения InvocationTargetException . Давайте попробуем понять это на примере.

Давайте напишем класс с методом, который намеренно создает исключение:

Теперь давайте вызовем описанный выше метод, используя отражение в простом тесте JUnit 5:

В приведенном выше коде мы утвердили исключение InvocationTargetException , которое возникает при вызове метода. Здесь важно отметить, что фактическое исключение – ArithmeticException в данном случае – оборачивается в InvocationTargetException.

Теперь вопрос, который приходит на ум, заключается в том, почему отражение не создает фактическое исключение в первую очередь?

Причина в том, что это позволяет нам понять, произошло ли Исключение из-за сбоя при вызове метода через слой отражения или оно произошло внутри самого метода.

3. Как обрабатывать исключение InvocationTargetException?

Здесь фактическое базовое исключение является причиной InvocationTargetException , поэтому мы можем использовать Throwable.getCause () , чтобы получить дополнительную информацию об этом.

Давайте посмотрим, как мы можем использовать getCause() для получения фактического исключения в том же примере, который использовался выше:

Здесь мы использовали метод getCause() для того же объекта exception , который был брошен. И мы утверждали ArithmeticException.class как причина исключения.

Таким образом, как только мы получим базовое исключение, мы можем перестроить его, обернуть в какое-то пользовательское исключение или просто зарегистрировать исключение в соответствии с нашими требованиями.

4. Заключение

В этой короткой статье мы рассмотрели, как слой отражения обертывает любое базовое исключение. Мы также видели, как определить основную причину исключения InvocationTargetException и как справиться с таким сценарием на простом примере.

Как обычно, код, используемый в этой статье, доступен на GitHub .

Источник

Java Exception Handling – InvocationTargetException

Moving along through our in-depth Java Exception Handling series, today we’ll take a closer look at the java.lang.reflect.InvocationTargetException. The java.lang.reflect.InvocationTargetException is thrown when working with the reflection API while attempting to invoke a method that throws an underlying exception itself.

In this article we’ll explore the InvocationTargetException in more detail by looking at where it resides in the Java Exception Hierarchy. We’ll also dig into a few functional reflection code samples that will illustrate how java.lang.reflect.InvocationTargetExceptions are typically thrown, showing how you might handle them in your own code, so let’s get crackin’!

The Technical Rundown

  • All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein.
  • java.lang.Exception inherits from java.lang.Throwable .
  • java.lang.ReflectiveOperationException inherits from java.lang.Exception .
  • Finally, java.lang.reflect.InvocationTargetException inherits from java.lang.ReflectiveOperationException .
Читайте также:  Last day on earth survival как начать заново андроид

When Should You Use It?

Since the InvocationTargetException deals with reflection, let’s briefly talk a bit about that practice and why explicitly invoking a method via reflection might be useful. In the most basic sense, reflection allows the JVM and your underlying code to inspect classes, methods, interfaces, and the like during runtime, without having directly called or identified those objects during compilation. This powerful capability means that your code can find classes and invoke methods that it wasn’t originally designed to handle out of the box.

To illustrate how invocation in Java works we have a few basic examples. To keep things simple, we’ll start with the full working code sample below, after which we’ll break it down in more detail to see what’s really going on:

As briefly mentioned in the introduction, an InvocationTargetException is automatically generated by reflection-related objects, and wraps (or attaches) itself to the underlying, actual exception type that caused the problem. This occurs when calling the java.lang.reflect.Method.invoke() method, where that invocation target method throws an exception.

To illustrate the issue we’ve got a basic Book class with a few property getter/setter methods, along with a some extraneous methods ( getTagline() and throwException() ) that we’ll explicitly call in the rest of our code:

The invokeGetTaglineMethod() method shows a basic, working example of using Java reflection to invoke() a class instance method ( Book.getTagline() , in this case).

The comments explain most everything that we’re doing, but the basic idea is that we starting by creating a Book instance object of book . We then need to instantiate a Class object, so we get a reflection of io.airbrake.Book , from which we can retrieve the declared getTagline() method. Using that Method instance of getTagline() we’re able to invoke() the method. Since this is an instance method, we need to pass an instance of the object as the first argument, so this is where we use the book object that was created at the beginning.

Executing this code results in the book object output, followed by the output from calling getTagline.invoke(book) , as expected:

Now that we’ve seen how invocation works, let’s try invoking a different Book instance method, specifically the Book.throwException() method. As its name suggests, Book.throwException() merely throws an Exception , using the passed String argument for the message:

To test this we’ll execute the invokeThrowExceptionMethod() method, which performs almost exactly the same code as our previous example, except the calls to getDeclaredMethod() and invoke() differ slightly since we’re also passing arguments to the invoked method:

Since the Book.throwException() method we’re invoking explicitly throws an error, our expectation is that executing the above code will result in a java.lang.reflect.InvocationTargetException being thrown. Sure enough, that’s exactly what happens:

Normally we’d only catch the parent InvocationTargetException in this scenario, which indicates the it was «Caused by: java.lang.Exception . » . However, a Throwable object implements the getCause() method, which returns the causal exception (if applicable). In the case of a InvocationTargetException instance, the cause is always the underlying exception object that occurred inside the invoked method, so checking for a cause when catching such exceptions is a good idea.

Читайте также:  Android textview wrap content height

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring , Maven , log4j , Struts , Kotlin , Grails , Groovy , and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices! Try Airbrake free for 30 days.

Monitor Your App Free for 30 Days

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.

Источник

Invocation Target Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs an InvocationTargetException with null as the target exception.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs an InvocationTargetException with null as the target exception.

Constructs an InvocationTargetException with null as the target exception.

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable) Class (Inherited from Throwable) Clause Handle

The handle to the underlying Android instance.

(Inherited from Throwable) JniIdentityHashCode (Inherited from Throwable) JniPeerMembers LocalizedMessage

Creates a localized description of this throwable.

(Inherited from Throwable) Message

Returns the detail message string of this throwable.

(Inherited from Throwable) PeerReference (Inherited from Throwable) StackTrace (Inherited from Throwable) TargetException

Get the thrown target exception.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable) Dispose() (Inherited from Throwable) Dispose(Boolean) (Inherited from Throwable) FillInStackTrace()

Fills in the execution stack trace.

(Inherited from Throwable) GetStackTrace()

Provides programmatic access to the stack trace information printed by #printStackTrace() .

(Inherited from Throwable) GetSuppressed()

Returns an array containing all of the exceptions that were suppressed, typically by the try -with-resources statement, in order to deliver this exception.

(Inherited from Throwable)

Читайте также:  Трекер времени для андроид
InitCause(Throwable)

Initializes the cause of this throwable to the specified value.

(Inherited from Throwable) PrintStackTrace()

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) PrintStackTrace(PrintStream)

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) PrintStackTrace(PrintWriter)

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Throwable) SetStackTrace(StackTraceElement[])

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable) ToString() (Inherited from Throwable) UnregisterFromRuntime() (Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Throwable)
IJavaPeerable.Finalized() (Inherited from Throwable)
IJavaPeerable.JniManagedPeerState (Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

java.lang.reflect.invocationtargetexception – How to handle Invocation Target Exception

Posted by: Sotirios-Efstathios Maneas in exceptions December 31st, 2013 0 Views

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java Virtual Machine. The reflection layer wraps any thrown exception as an InvocationTargetException . In this way, it is clear whether the exception was actually caused by a failure in the reflection call, or a failure within the method called.

The InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. The thrown exception is provided at construction time and can be accessed via the getTargetException method. That exception is known as the cause and can be accessed via the getCause method.

For more information about the reflection in Java, please refer to the page here .

Error case

The following code snippet throws an InvocationTargetException :

The result of the above snippet is:

If we carefully observe the code, we will understand why the InvocationTargetException was thrown. Initially, we get an instance of the ReflectionExample class. Then, we iterate over its declared methods and we call the method under the name testMethod , passing an empty String as an argument.

However, the testMethod throws an IllegalArgumentException , in case the length of the string equals to zero. That exception is wrapped as an InvocationTargetException and is thrown in our sample application.

If we change the 39 th line to:

the execution continues without any exception being thrown. As a result, we get the following result:

How to deal with the exception

First of all, coding an application using reflection is hard. A developer must have a strong grasp of the internal structure of the Java programming language, because the usage of reflection contains drawbacks and dangers, such as performance overhead and exposure of internal fields and methods.

If you decide to use reflection, consider enclosing your code inside a try-catch statement and manipulate the InvocationTargetException accordingly. Notice that the result of the getCause method can be one of the following:

In your application’s code, make sure that you check for all aforementioned cases, otherwise your code may produce undesired bugs.

Источник

Оцените статью