Recipe7.6.Handling Exceptions Thrown from Methods Invoked via Reflection


Recipe 7.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 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 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(TargetInvocationException 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("\tINNEREXCEPTION MESSAGE: " +                                   e.InnerException.Message);                 Console.WriteLine("\tINNEREXCEPTION SOURCE: " +                                   e.InnerException.Source);                 Console.WriteLine("\tINNEREXCEPTION STACK: " +                                   e.InnerException.StackTrace);                 Console.WriteLine("\tINNEREXCEPTION TARGETSITE: " +                                   e.InnerException.TargetSite);                 Console.WriteLine("\t**** INNEREXCEPTION END ****");             }             Console.WriteLine( );                          // Shows fusion log when assembly cannot be located             Console.WriteLine(e.ToString( ));         }     }     // Method to invoke via reflection     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. SOURCE: mscorlib TARGET: System.Object _InvokeMethodFast(System.Object, System.Object[], System. SignatureStruct ByRef, System.Reflection.MethodAttributes, System.RuntimeTypeHandle) STACK:   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes,    RuntimeTypeHandle typeOwner)     at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, SignatureStruct sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)     at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)     at CSharpRecipes.ExceptionHandling.ReflectionException() in         C:\C#Cookbook2\CSharpRecipes\07_ExceptionHandling.cs:line 195              **** INNEREXCEPTION START ****     INNEREXCEPTION MESSAGE: Thrown from invoked method.     INNEREXCEPTION SOURCE: CSharpRecipes     INNEREXCEPTION STACK: at CSharpRecipes.ExceptionHandling.TestInvoke() in         C:\C#Cookbook2\CSharpRecipes\07_ExceptionHandling.cs:line 226     INNEREXCEPTION TARGETSITE: Void TestInvoke()     **** INNEREXCEPTION END **** 

When the methodToInvoke.Invoke method is called, the TestInvoke method is called. It throws an exception. The outer exception is the TargetInvocationException; this is the generic exception thrown when a method invoked through reflection throws an exception. The CLR automatically wraps the original exception thrown by the invoked method inside of the TargetInvocationException object's InnerException property. In this case, the exception thrown by the invoked method is of type System.Exception. This exception is shown after the section that begins with the text **** INNEREXCEPTION START ****.

In addition to this text, the code also calls e.ToString to print out the exception text. The text output from ToString is:

 System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: Thrown from invoked method.     at ClassLibrary1.Reflect.TestInvoke( ) in         C:\BOOK CS CookBook\Code\Test.cs:line 49     at ClassLibrary1.Reflect.TestInvoke( ) in         C:\BOOK CS CookBook\Code\Test.cs:line 49     --- End of inner exception stack trace --     at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags       invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean       isBinderDefault, Assembly caller, Boolean verifyAccess)     at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags       invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean       verifyAccess)     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr,       Binder binder, Object[] parameters, CultureInfo culture)     at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)     atReflect.ReflectionException( ) in c:\book cs cookbook       \code\test.cs:line 22 

Using the ToString method is a quick and simple way of displaying the most relevant outer exception information along with the most relevant information for each inner exception.

See Also

See the "Type Class" and "MethodInfo Class" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net