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?
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.