我正在通过反射调用一个可能导致异常的方法.如何在没有包装反射的情况下将异常传递给调用方?
我正在重新引发InnerException,但这会 destruct 堆栈跟踪.
示例代码:

public void test1()
{
    // Throw an exception for testing purposes
    throw new ArgumentException("test1");
}

void test2()
{
    try
    {
        MethodInfo mi = typeof(Program).GetMethod("test1");
        mi.Invoke(this, null);
    }
    catch (TargetInvocationException tiex)
    {
        // Throw the new exception
        throw tiex.InnerException;
    }
}

推荐答案

.NET 4.5班现在有ExceptionDispatchInfo班.

这允许您捕获异常并重新抛出它,而无需更改堆栈跟踪:

using ExceptionDispatchInfo = 
    System.Runtime.ExceptionServices.ExceptionDispatchInfo;

try
{
    task.Wait();
}
catch(AggregateException ex)
{
    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}

这对任何异常都有效,而不仅仅是AggregateException个.

它的引入源于await C#语言特性,它从AggregateException个实例中打开内部异常,以使异步语言特性更像同步语言特性.

.net相关问答推荐

DI通过对象的接口而不是实际类型来解析服务

在计算Total毫秒时,.NET TimeSpan类中是否存在错误?

Azure Function应用程序-如何升级.NET运行时

从窗体中移除另一个控件中引用的控件时获取设计时通知

CustomControl 计算自己的宽度和高度 - 使用 bounds.Height=0 调用 ArrangeOverride

如何找到windows服务exe路径

使用字典作为数据源绑定组合框

为什么 SortedSet.GetViewBetween 不是 O(log N)?

如何通过 LINQ 比较没有时间的 DateTime?

在 C# 中转义命令行参数

是否有 TLS 1.2 的 .NET 实现?

新的 netstandardapp 和 netcoreapp TFM 有什么区别?

如何将枚举值序列化为 int?

什么是 C# 中的自动属性,它们的用途是什么?

等效于 C# 在 powershell 中的使用关键字?

使用+运算符的字符串连接

WebClient.DownloadString 由于编码问题导致字符损坏,但浏览器正常

忽略 LINQ to XML 中的命名空间

从 Visual Studio 2015 发布 - 允许不受信任的证书

名称 <...> 不存在于命名空间 clr-namespace <...>