5.6. 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 exception 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 here:

using System; using System.Reflection; public class Reflect { public void ReflectionException( ) { Type reflectedClass = typeof(Reflect); try { MethodInfo methodToInvoke = reflectedClass.GetMethod("TestInvoke"); if (methodToInvoke != null) { object oInvoke = methodToInvoke.Invoke(null, null); } } catch(Exception e) { Console.WriteLine("MESSAGE: " + e.Message); Console.WriteLine("SOURCE: " + e.Source); Console.WriteLine("TARGET: " + e.TargetSite); Console.WriteLine("STACK: " + e.StackTrace + "\r\n"); if(e.InnerException != null) { Console.WriteLine( ); Console.WriteLine("\t**** INNEREXCEPTION START ****"); Console.WriteLine("\tTYPE THAT THREW EXCEPTION: " + reflectedClass.ToString( )); Console.WriteLine("\tINNEREXCEPTION MESSAGE: " + e.InnerException.Message); Console.WriteLine("\tINNEREXCEPTION SOURCE: ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.