How to rethrow InnerException without losing stack trace in C#?(如何在 C# 中重新抛出 InnerException 而不会丢失堆栈跟踪?)
问题描述
我正在通过反射调用一个可能导致异常的方法.如何在没有包装反射的情况下将异常传递给调用者?
我正在重新抛出 InnerException,但这会破坏堆栈跟踪.
示例代码:
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it?
I am rethrowing the InnerException, but this destroys the stack trace.
Example code:
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 类.
In .NET 4.5 there is now the ExceptionDispatchInfo class.
这让您可以在不更改堆栈跟踪的情况下捕获异常并重新抛出它:
This lets you capture an exception and re-throw it without changing the stack-trace:
using ExceptionDispatchInfo = 
    System.Runtime.ExceptionServices.ExceptionDispatchInfo;
try
{
    task.Wait();
}
catch(AggregateException ex)
{
    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
这适用于任何异常,而不仅仅是 AggregateException.
This works on any exception, not just AggregateException.
它是由于 await C# 语言特性而引入的,它从 AggregateException 实例中解包内部异常,以使异步语言特性更像同步语言特性.
It was introduced due to the await C# language feature, which unwraps the inner exceptions from AggregateException instances in order to make the asynchronous language features more like the synchronous language features.
这篇关于如何在 C# 中重新抛出 InnerException 而不会丢失堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中重新抛出 InnerException 而不会丢失堆栈
				
        
 
            
        基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
 - 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
 - 错误“此流不支持搜索操作"在 C# 中 2022-01-01
 - 全局 ASAX - 获取服务器名称 2022-01-01
 - 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
 - 首先创建代码,多对多,关联表中的附加字段 2022-01-01
 - 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
 - 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
 - JSON.NET 中基于属性的类型解析 2022-01-01
 - 如何动态获取文本框中datagridview列的总和 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				