7.3. Handling Exceptions Thrown from Methods Invoked via Reflection
Problem
Using reflection, you invoke a method that generates an exception. You want to obtain the real exception object and its information in order to diagnose and fix the problem.
Solution
The real exception and its information can be obtained through the InnerException property of the TargetInvocationException that is thrown by MethodInfo.Invoke.
Discussion
The following example shows how an exception that occurs within a method invoked via reflection is handled. The Reflect class contains a ReflectionException method that invokes the static TestInvoke method using the reflection classes as shown in Example 7-2.
Example 7-2. Obtaining information on an exception invoked by a method accessed through reflection
using System;
using System.Reflection;
public static class Reflect
{
public static void ReflectionException()
{
Type reflectedClass = typeof(ExceptionHandling);
try
{
MethodInfo methodToInvoke = reflectedClass.GetMethod("TestInvoke");
if (methodToInvoke != null)
{
methodToInvoke.Invoke(null, null);
}
}
catch(Exception e)
{
Console.WriteLine(e.ToShortDisplayString());
}
}
public static void TestInvoke()
{
throw (new Exception("Thrown from invoked method."));
}
}This code displays the following text:
Message: Exception has been thrown by the target of an invocation. Type: System.Reflection.TargetInvocationException Source: mscorlib TargetSite: System.Object _InvokeMethodFast(System.Object, System.Object[], Syst ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access