如何捕获使用MethodInfo.Invoke调用的方法抛出的异常?

时间:2014-12-02 04:43:14

标签: c# exception reflection try-catch invoke

我有以下代码:

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 Method2 都执行 MyClass.MyMethod ,但 Method1 输出:

Invalid argument -3

Method2 输出:

Exception has been thrown by the target of an invocation.

我们可以修改 Method2 ,以便能够像 Method1 一样捕获异常吗?

1 个答案:

答案 0 :(得分:4)

看看InnerException。在.NET中,反射将包装异常 - 这对于了解如何调用异常非常有用。查看内部异常属性是否有您要查找的异常。 stack trace

因此,要获得相同的例外,请改为调用Console.WriteLine(e.InnerException.Message)