How to print call hierarchy in Java?

In debugging, it is essential to know the call hierarchy of a particular method i.e. which method is calling that method which is technically called as Stack trace.


In this post we will see 2 ways to get the stack trace.

Thread.getStackTrace()
Exception.printStackTrace()

ThreadStackTraceDemo.java

import java.util.Arrays;
public class ThreadStackTraceDemo {
    public static void main(String args[]) {
      method1();
    }
    
    static void method2() 
    {
        System.out.println("In method2()");
        System.out.println(Arrays.toString(Thread.currentThread().getStackTrace()));
    }
    
    static void method1() {
        method2();
    }
}

Thread.currentThread() - Returns the current thread object and getStackTrace() returns the StackTraceElement[] which can be printed as String using Arrays.toString()

ExceptionStackTraceDemo.java

public class ExceptionStackTraceDemo {
    public static void main(String args[]) {
      method1();
    }
    
    static void method2() 
    {
        System.out.println("In method2()");
        try {
            throw new Exception("Test Exception for getting call hierarchy");
        } catch(Exception ex) {
            ex.printStackTrace();   
        }
    }
    
    static void method1() {
        method2();
    }
}

Here, we throw a Test exception to just know the call hierarchy. If you are using a logger, you can use the following method to log the stack trace.

StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
log.error(sw.toString());

Output

In method2()
java.lang.Exception: Test Exception for getting call hierarchy
	at ExceptionStackTraceDemo.method2(ExceptionStackTraceDemo.java:12)
	at ExceptionStackTraceDemo.method1(ExceptionStackTraceDemo.java:22)
	at ExceptionStackTraceDemo.main(ExceptionStackTraceDemo.java:5)

ధన్యవాదాలు (Thanks)

No comments: