C#: 保留堆栈跟踪重新抛出异常变量

3

在我的代码库中,我有一些重试功能,它会将异常存储在变量中,并在最后将该变量中的异常抛出。类似于以下情况:

Exception exc = null;

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

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

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

InnerException? - Sinatr
但是这样我就会失去类型信息,因此查看类型的异常处理程序将无法看到原始类型。 - MrZarq
原始异常 eStackTrace 属性中不会包含堆栈跟踪吗? - arconaut
1
这里的被采纳答案或许会有所帮助。链接 - Klaus Gütter
1个回答

8
那就需要用到 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
  • throw new Exception("A"); 被调用的代码在第16行。
  • edi?.Throw(); 被调用的代码在第24行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接