传递ExceptionDispatchInfo而不仅仅是Exception有什么意义?

时间:2017-08-16 21:31:46

标签: c# .net exception-handling

我理解ExceptionDispatchInfo.Capture(e).Throw()的值(保留原始堆栈跟踪),但是早期使用Capture并传递ExceptionDispatchInfo而不是仅传递被捕获的Exception有什么好处static Exception CaptureException(Action action) { try { action(); return null; } catch (Exception e) { return e; } } public void Test1() { ExceptionDispatchInfo.Capture(CaptureException( () => throw new IOException("Test"))) .Throw(); } 1}}周围?

作为一个具体的例子,比较

static ExceptionDispatchInfo CaptureDispatchInfo(Action action)
{
  try
  {
    action();
    return null;
  }
  catch (Exception e)
  {
    return ExceptionDispatchInfo.Capture(e);
  }
}

public void Test2()
{
  CaptureDispatchInfo(() => throw new IOException("Test")).Throw();
}

async

,两者都给出了基本相同的堆栈跟踪(它与此类ExceptionDispatchInfo变体相似。)。所以,我真的不明白为什么ExceptionDispatchInfo.Capture(e).Throw()类存在,而不仅仅是一个组合的extern/static inline/_Noreturn myfunction(){}; 方法。

2 个答案:

答案 0 :(得分:1)

ExceptionDispatchInfo用于在引发Exception之后保留堆栈跟踪,允许您捕获该异常,而不是立即将其抛出(作为catch的一部分),并在以后的稍后时间引发此类异常。 / p>

我在https://thorarin.net/blog/post/2013/02/21/Preserving-Stack-Trace.aspx上找到了一个很好的例子。

答案 1 :(得分:1)

您假设异常是不可变的。情况并非如此-异常的StackTrace在重新抛出时会更改。

ExceptionDispatchInfo.Capture的目的是在某个时间点捕获潜在变异的异常的StackTrace:

void Foo() => throw new InvalidOperationException ("foo");

Exception original = null;
ExceptionDispatchInfo dispatchInfo = null;
try
{
    try
    {
        Foo();
    }
    catch (Exception ex)
    {
        original = ex;
        dispatchInfo = ExceptionDispatchInfo.Capture (ex);
        throw ex;
    }
}
catch (Exception ex2)
{
    // ex2 is the same object as ex. But with a mutated StackTrace.
    Console.WriteLine (ex2 == original);  // True
}

// So now "original" has lost the StackTrace containing "Foo":
Console.WriteLine (original.StackTrace.Contains ("Foo"));  // False

// But dispatchInfo still has it:
try
{
    dispatchInfo.Throw ();
}
catch (Exception ex)
{
    Console.WriteLine (ex.StackTrace.Contains ("Foo"));   // True
}