首页 > 解决方案 > C# 为什么 Exception.StackTrace 不包含完整的堆栈跟踪?

问题描述

我从MSDN读到:

StackTrace 属性返回调用堆栈的帧,这些帧源自引发异常的位置

引用对我来说不是很清楚,所以让我们看一个例子:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            A();
        }
        catch (Exception e)
        {
            Console.WriteLine("second catch. Stacktrace: {0}", e.StackTrace);
        }
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public static void A()
    {
        try
        {
            throw new Exception();
        }
        catch (Exception e)
        {
            Console.WriteLine("first catch. Stacktrace: {0}", e.StackTrace);
            throw;
        }
    }
}

输出:(隐藏的'in'块)

first catch. Stacktrace:    
   at TestExceptions.Program.A()
second catch. Stacktrace:    
   at TestExceptions.Program.A()
   at TestExceptions.Program.Main(String[] args)

第一个 catch 块中的 Exception.StackTrace 不包含完整的堆栈跟踪,包括“Main”方法调用。更一般地说,Exception.StackTrace 仅包含捕获块和抛出位置之间的堆栈帧。

有谁知道,为什么选择这样的决定?由于性能问题,还是有其他问题?

更新:

问题与那个问题不同。我想知道为什么选择那个 exception.StackTrace 会返回堆栈的一部分。

标签: c#exceptionarchitecture

解决方案


推荐阅读