gpt4 book ai didi

c# - 如何在不丢失 C# 堆栈跟踪的情况下重新抛出 InnerException?

转载 作者:IT王子 更新时间:2023-10-29 03:28:30 25 4
gpt4 key购买 nike

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

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 实例中解包内部异常,以使异步语言特性更像同步语言特性.

关于c# - 如何在不丢失 C# 堆栈跟踪的情况下重新抛出 InnerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com