【问题标题】:Exception has been thrown by the target of an invocation (MethodBase.Invoke Method)调用的目标(MethodBase.Invoke 方法)引发了异常
【发布时间】:2026-02-04 03:20:03
【问题描述】:

我想捕获在调用方法调用的方法中抛出的异常。

public void TestMethod()
{
   try     
   {
       method.Invoke(commandHandler, new[] { newCommand });
   }
   catch(Exception e)
   {     
       ExceptionService.SendException(e);
   }
}

method.Invoke 调用以下方法:

public void Register(/*parameters*/)
{
     if(test_condition())
          throw new CustomException("Exception Message");
}

问题是当我在TestMethod 中捕获CustomException 时,catch 语句中的e 变量没有CustomException 类型。它具有以下消息:“调用的目标已引发异常”。

我想捕获已引发的异常(即 CustomException),并将其传递给 ExceptionService 机制。

我做错了什么?

【问题讨论】:

    标签: c# exception reflection invoke


    【解决方案1】:

    是的,您正在通过反射调用该方法。所以按照the documentation,如果目标方法抛出异常,就会抛出TargetInvocationException

    只需使用 InnerException 属性来获取 - 并可能抛出 - 原始异常。

    例如:

    try     
    {
        method.Invoke(commandHandler, new[] { newCommand });
    }
    catch (TargetInvocationException e)
    {     
        ExceptionService.SendException(e.InnerException);
    }
    

    【讨论】: