January 2004
Beginner to intermediate
864 pages
22h 18m
English
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.
The real exception and its information can be obtained through the
InnerException
property of the
TargetInvocationException
exception that is thrown by MethodInfo.Invoke.
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: ...