How do stack traces get generated?

后端 未结 4 1906
盖世英雄少女心
盖世英雄少女心 2021-01-20 23:53

No single method in a program \"knows\" where it is on the stack. All it knows is its own little job, and it does that and returns. So when an Exception is thrown and a stack

相关标签:
4条回答
  • 2021-01-21 00:14

    It comes from the Thread class that is running through the code.

    Thread.dumpStack();
    

    To see it you can just:

        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        for (int i=0; i < trace.length; i++)
            System.out.println("\tat " + trace[i]);
    
    0 讨论(0)
  • 2021-01-21 00:20

    Every thread will have its own stack. Each method call creates a stack frame. If something wrong happened in code of any method, that will propagated to caller method. This way JVM can trace which method generated error and what is the call hierarchy.

    If you observe the stack trace properly, you will see the method where error occured at top and the hierarchy in bottom.

    There is a great lecture in youtube by a Stanford professor to understand how does it work. I would suggest watching it.

    NOTE: This is theory. If you would like to know how API works, @Peter Lawrey answer may help you.

    0 讨论(0)
  • 2021-01-21 00:34

    You can know the Thread a method belongs to by using Thread.currentThread. Using this thread, you can get the StackTrace, because there is a stack for every thread in the JVM. Also, the main program runs in the main thread.

    0 讨论(0)
  • 2021-01-21 00:37

    When you create a Throwable (not when you throw it) it records the stack trace is a low level/hidden way associated with the Throwable. When you call getStackTrace() the first time it creates the StackTraceElement[] objects from the low level information. It doesn't this lazily as the stack trace is often not used.

    0 讨论(0)
提交回复
热议问题