O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required