简体   繁体   English

如何捕获在使用MethodInfo.Invoke调用的方法中引发的异常?

[英]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: 方法1方法2都执行MyClass.MyMethod,方法一输出:

Invalid argument -3

while Method2 outputs: Method2输出:

Exception has been thrown by the target of an invocation.

Could we modify Method2 so it could catch the exception as in Method1 ? 我们可以修改Method2以便它可以像Method1一样捕获异常吗?

Take a look at the InnerException . 看一下InnerException In .NET reflection will wrap the exception - which can be useful for knowing how the exception was called. 在.NET中,反射将包装异常-这对于了解异常的调用方式很有用。 See the inner exception property has the exception you are looking for. 请参阅内部异常属性具有您要查找的异常。 堆栈跟踪

So to have the same exception just call Console.WriteLine(e.InnerException.Message) instead. 因此,要具有相同的异常,只需调用Console.WriteLine(e.InnerException.Message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM