如何在不重置堆栈跟踪的情况下抛出异常?

2024-02-02

这是一个后续问题“扔”和“扔前”有区别吗 https://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex?

有没有办法在不重置堆栈跟踪的情况下提取新的错误处理方法?

[EDIT]我将尝试“内部方法”和另一种answer https://stackoverflow.com/questions/730300/how-to-throw-exception-without-resetting-stack-trace/730385#730385由 Earwicker 提供,看看哪一个可以更好地标记答案。


在 .NET Framework 4.5 中,现在有一个异常调度信息 http://msdn.microsoft.com/en-us/library/system.runtime.exceptionservices.exceptiondispatchinfo.aspx它支持这个确切的场景。它允许捕获完整的异常并从其他地方重新抛出它,而不会覆盖所包含的堆栈跟踪。

根据评论中的要求提供代码示例

using System.Runtime.ExceptionServices;

class Test
{
    private ExceptionDispatchInfo _exInfo;

    public void DeleteNoThrow(string path)
    {
        try { File.Delete(path); }
        catch(IOException ex)
        {
            // Capture exception (including stack trace) for later rethrow.
            _exInfo = ExceptionDispatchInfo.Capture(ex);
        }
    }

    public Exception GetFailure()
    {
        // You can access the captured exception without rethrowing.
        return _exInfo != null ? _exInfo.SourceException : null;
    }

    public void ThrowIfFailed()
    {
        // This will rethrow the exception including the stack trace of the
        // original DeleteNoThrow call.
        _exInfo.Throw();

        // Contrast with 'throw GetFailure()' which rethrows the exception but
        // overwrites the stack trace to the current caller of ThrowIfFailed.
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在不重置堆栈跟踪的情况下抛出异常? 的相关文章

随机推荐