C#:从变量中重新抛出异常,同时保留堆栈跟踪

标签 c# .net exception

在我的代码库中,我有一些重试功能,将异常存储在变量中,最后在变量中抛出异常。想象一下这样的事情

Exception exc = null;

while(condition){
   try {
      // stuff
   } catch (Exception e){
     exc = e;
   }
}

if (e != null){
   throw e;
}

现在,由于这是一个 throw e 语句而不是 throw 语句,原始堆栈跟踪丢失了。是否有某种方法可以进行重新抛出以保留原始堆栈跟踪,或者我需要重组我的代码以便我可以使用 throw 语句?

最佳答案

这就是ExceptionDispatchInfo发挥作用。
它位于 System.Runtime.ExceptionServices 命名空间内。

class Program
{
    static void Main(string[] args)
    {
        ExceptionDispatchInfo edi = null;

        try
        {
            // stuff
            throw new Exception("A");
        }
        catch (Exception ex)
        {
            edi = ExceptionDispatchInfo.Capture(ex);
        }

        edi?.Throw();
    }
}

输出:

Unhandled exception. System.Exception: A
   at EDI_Demo.Program.Main(String[] args) in C:\Users\...\Program.cs:line 16
--- End of stack trace from previous location where exception was thrown ---
   at EDI_Demo.Program.Main(String[] args) in C:\Users\...\Program.cs:line 24
  • 第 16 行是调用 throw new Exception("A"); 的地方
  • 第 24 行是调用 edi?.Throw(); 的地方

关于C#:从变量中重新抛出异常,同时保留堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64913559/

相关文章:

c# - 在中间件中序列化对 JSON 的响应的最佳方法是什么?

c# - 使用 WCF 在另一个 CLR 地址空间中执行代码并返回对象

java - 判断一个URL是否存在?

c# - 是否通过存储库/服务/其他持久化 XML/CSV/其他

java - .NET ListBox 的 Swing 等价物

java - 为什么 writeObject 会抛出 java.io.NotSerializableException,我该如何解决?

c++ - 在 C++ 类的构造函数中引发异常

c# 如何处理网络中断

c# - 高效快速地阅读 Windows 日志

c# - JWT token 身份验证失败,并显示消息 "PII is hidden"