什么是堆栈跟踪?

3

可能是重复问题:
调用堆栈决定了下一步的去向?

这个问题的评论开始,我以为我知道什么是堆栈跟踪,但我想我并不知道。我在谷歌上搜索了它,但找不到清晰的答案。

@asawyer说

堆栈跟踪不确定你已经经过哪里,而是告诉你下一步要去哪里。

这是一个小程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Method1();
        }

        private static void Method1()
        {
            Method2();
        }

        private static void Method2()
        {
            Random rnd = new Random();
            int i = rnd.Next(0, 100);

            throw new Exception();

            if (i > 50)
                Method3();
            else
                Method4();
        }

        private static void Method3(){ }

        private static void Method4(){ }
    }
}

这将产生如下的堆栈跟踪。
   at ConsoleApplication1.Program.Method2() in C:\Users\Ash Burlaczenko\Desktop\CSSD\Assignment 3\ConsoleApplication1\ConsoleApplication1\Program.cs:line 25
   at ConsoleApplication1.Program.Method1() in C:\Users\Ash Burlaczenko\Desktop\CSSD\Assignment 3\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17
   at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Ash Burlaczenko\Desktop\CSSD\Assignment 3\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

尽管在异常发生时,代码可以根据已知的i的值计算出将要调用的方法,但堆栈跟踪并未提及未来的方法调用。
我对“堆栈跟踪告诉你代码所在位置”的想法错在哪里?

我想埃里克的意思是,你所采取的“下一步”(通常)是从堆栈顶部弹出时得到的步骤 - 也就是说,你从函数调用返回。 - Kerrek SB
2个回答

4

堆栈跟踪可以展示你所在的位置,假设你从当前函数正常返回,它也可以展示你最终会回到哪里。根据当前函数的内容,可能会有其他的东西先被执行(比如当前函数还未调用但是将要调用的函数),这些东西不会显示在堆栈跟踪中,直到你进入它们为止。


3

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