How to get current stack trace in Java

April 7, 2017

In general, we can get our stack trace by calling a method:

1. What a stack trace is?

The stack trace is a report of methods calls in our application. So in simple words: it can tell us where exactly our program is at the point of doing something. Sometimes it is needed when we need control while debugging our application. We can see where exactly an error occurs, where something when wrong and repair it quickly.

2. How to get a stack trace?

Let’s say our program has got main and three other methods. Each method calls next one in its body:

Now we want to see how our program goes through these methods. Using the function Thread.currentThread().getStackTrace() it’s very simple. We need to create the table of our stack elements to know WhereWeAre then display necessary information in a for loop.

Declaring table

After that, we will create a stack trace object to get the exact place in a loop:
Then, we can display needed information. The most important for us will be getMethodName() but we can add anything we want at this moment. For example, getFileName() or getLineNumber().
If we put this code in each method, we will always get current stack trace!
This code prints:
Click here to add a comment

Leave a comment: