When you debug a complex Java code which has some parallel threads running, it is not easy to capture all the breakpoints and sometimes it is really hard to find which path has caused the problem. In such a scenarios, we need to print the method call stack at suspected locations. How can I print the method call stack within Java?
The printStackTrace() method of Java. lang. Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred means its backtrace. This method prints a stack trace for this Throwable object on the standard error output stream.
The call stack is what a program uses to keep track of method calls. The call stack is made up of stack frames—one for each method call. For instance, say we called a method that rolled two dice and printed the sum. def roll_die(): return random.
We can obtain a stack trace from a thread by calling the getStackTrace() method on the Thread instance. It returns an array of StackTraceElement, from which details about stack frames of the thread can be found.
The call stack of the running Java program is modelled by three interfaces: Frame, which encapsulates the data stored in a single stack frame, such as the operand stack and local variables; FrameSource, which encapsulates the allocation and layout of Frames, controlling such things as the argument-passing mechanism; ...
Here is how you print the stack trace from a given location in your source file.
System.out.println("Printing stack trace:");
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (int i = 1; i < elements.length; i++) {
StackTraceElement s = elements[i];
System.out.println("\tat " + s.getClassName() + "." + s.getMethodName() + "(" + s.getFileName() + ":" + s.getLineNumber() + ")");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With