How to Use StackTraceElement in Java for Debugging

Tuesday May 4th 2021 by MS Sridhar
Article Image

Tracking down bugs in code can be hard. To help with this issue, we are going to look at Java’s built-in utility for debugging: StackTraceElement.

Programming in Java can be fun, but when it comes to tracking down bugs or issues in code, it can be a bit of a nightmare. To help with this issue, we are going to look at Java’s built-in utility for debugging: StackTraceElement and learn how to use it for common debugging.

Java has built-in support to make the debugging process easier, thanks in part to its utility class, StackTraceElement. We illustrate below how to find out which method - and also the line number - that is currently being executed to help us better troubleshoot our code.

Here is a code sample showing how to use StackTraceElement to debug and track down problems in your Java code:


public class StackTraceElementUsage{

	public static void main(String []args){
		StackTraceElementUsage stackTraceElementUsage = new StackTraceElementUsage();

	private void proceed()
      try {
        int quotient = 10/5;

        int currentStackTraceSize = Thread.currentThread().getStackTrace().length;
        StackTraceElement currentStackTrace = null;
        for (int i=0; i<currentStackTraceSize; i++)
            currentStackTrace = Thread.currentThread().getStackTrace()[i];
            System.out.println("["+i+"] MethodName: " + currentStackTrace.getMethodName() 
                + ", LineNumber: " + currentStackTrace.getLineNumber());
        System.out.println("Quotient: " + quotient);
      catch (Throwable e) {


The following output demonstrates information you can get using Java’s StackTraceElement debugging utility:

$java StackTraceElementUsage
[0] MethodName: getStackTrace, LineNumber: 1559
[1] MethodName: proceed, LineNumber: 18
[2] MethodName: main, LineNumber: 5
Quotient: 2
Mobile Site | Full Site