How do stack traces get generated?

我与影子孤独终老i 提交于 2019-12-31 02:18:04

问题


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 trace is printed, where does this come from?

Is there implicitly a separate Thread running alongside of every application in the JVM that's monitoring the state of the program? Or does the JVM itself hold this information and the Exceptions somehow pull that data from it when they are thrown?

If either of these is the case, is it possible to use some call to retrieve a stack trace (either from the monitor Thread or the JVM) without throwing an Exception?


回答1:


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.




回答2:


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]);



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/12865180/how-do-stack-traces-get-generated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!