【问题标题】:C#: Rethrow an exception from a variable while preserving stack traceC#:从变量中重新抛出异常,同时保留堆栈跟踪
【发布时间】:2021-03-02 22:19:19
【问题描述】:

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

Exception exc = null;

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

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

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

【问题讨论】:

  • 但是我丢失了我的类型信息,所以查看类型的异常处理程序将看不到原始类型。
  • 原始异常e 是否在其StackTrace 属性中包含堆栈跟踪?
  • 接受的答案here 可能会有所帮助。

标签: c# exception


【解决方案1】:

这就是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(); 的位置

【讨论】:

    猜你喜欢
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多