2014-12-02 1 views
2

I는 다음과 같은 코드가 :MethodInfo.Invoke를 사용하여 호출 한 메서드에서 Throw 된 Exception을 catch하는 방법?

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 
    } 

    } 
} 

방법 항목모두 을 MyClass.MyMethod 실행 방법 2하지만 방법 항목 출력 :

Invalid argument -3 

동안 방법 2 출력 :

Exception has been thrown by the target of an invocation. 

2 방법 2을 수정할 수 있으므로 방법 1에서 예외를 catch 할 수 있습니까?

답변

4

InnerException을 살펴보십시오. .NET 리플렉션에서 예외를 래핑합니다 - 이는 예외가 호출 된 방법을 아는 데 유용 할 수 있습니다. 찾고있는 예외가 내부 예외 속성을 참조하십시오. stack trace

동일한 예외가 발생하면 대신 Console.WriteLine(e.InnerException.Message)으로 전화하십시오.

관련 문제