Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print java method call stack?

Tags:

java

debugging

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?

like image 560
Chanaka udaya Avatar asked Aug 29 '17 17:08

Chanaka udaya


People also ask

How do I print a stack trace?

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.

What is the method call stack in Java?

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.

How can I get the current stack trace in Java?

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.

Does Java have a call stack?

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


1 Answers

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() + ")");
}
like image 85
Chanaka udaya Avatar answered Oct 04 '22 11:10

Chanaka udaya