Setyo N
Setyo N

Reputation: 2103

How to catch Exception thrown in a method invoked by using MethodInfo.Invoke?

I have the following codes:

using System;
using System.Reflection;

namespace TestInvoke
{
  class Program
  {
    static void Main( string[] args )
    {
      Method1();
      Console.WriteLine();
      Method2();
    }

    static void Method1()
    {
      try
      {
        MyClass m = new MyClass();
        m.MyMethod( -3 );
      }
      catch ( Exception e )
      {
        Console.WriteLine( e.Message );
      }
    }

    static void Method2()
    {
      try
      {
        string className = "TestInvoke.MyClass";
        string methodName = "MyMethod";
        Assembly assembly = Assembly.GetEntryAssembly();
        object myObject = assembly.CreateInstance( className );
        MethodInfo methodInfo = myObject.GetType().GetMethod( methodName );
        methodInfo.Invoke( myObject, new object[] { -3 } );
      }
      catch ( Exception e )
      {
        Console.WriteLine( e.Message );
      }

    }
  }

  public class MyClass
  {
    public void MyMethod( int x )
    {
      if ( x < 0 )
        throw new ApplicationException( "Invalid argument " + x );

      // do something
    }

  }
}

Method1 and Method2 both execute MyClass.MyMethod, but Method1 outputs:

Invalid argument -3

while Method2 outputs:

Exception has been thrown by the target of an invocation.

Could we modify Method2 so it could catch the exception as in Method1?

Upvotes: 3

Views: 2975

Answers (1)

tophallen
tophallen

Reputation: 1063

Take a look at the InnerException. In .NET reflection will wrap the exception - which can be useful for knowing how the exception was called. See the inner exception property has the exception you are looking for. stack trace

So to have the same exception just call Console.WriteLine(e.InnerException.Message) instead.

Upvotes: 5

Related Questions