Google


   


You are here: CodeIdol.com > C# > C# Cookbook, 2nd Edition > Exception Handling > Handling Exceptions Thrown From Methods Invoked Via Reflection

SAVE
Digg
Shown on del.icio.us del.icio.us
See Whos Talking About This on Technorati Technorati
I've Reddit reddit

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.


SAVE
Digg
Shown on del.icio.us del.icio.us
See Whos Talking About This on Technorati Technorati
I've Reddit reddit

You are here: CodeIdol.com > C# > C# Cookbook, 2nd Edition > Exception Handling > Handling Exceptions Thrown From Methods Invoked Via Reflection


ADBRITE ads links
   
Related tags







Popular Categories
Unix books and guides

AJAX popular information
C# language guides
Windows books and cookbooks

.......








Business Key Top Sites

be number one
rate your site




    С 2009 года мы стали переводить структура сайта на различные языки. Сайт теперь будет содержать книги не только на английском языке, но также и на других европейских языках, в том числе и на Русском языке.

    Русский Polski Francais Deutsch
    support sitemap terms

© CodeIdol Labs, 2007 - 2009