figaro
figaro

Reputation: 2325

How to get stack trace from the caller in Java

In Java, I want to get the stack trace of how the calls were made to which methods. How can I achieve that?

For example, my call stack is:

class Example {
   public void init() {
      func1();
      // TODO : now here I want to print the stack trace that it went from:
      // func1
      // func2
      // func3
   }
   public void func1() {
      func2();
   }
   public void func2() {
      func3();
   }
   public void func3() {
      // some code here
   }
    

}

Upvotes: 1

Views: 138

Answers (2)

vishal rana
vishal rana

Reputation: 43

Use a IDE and make use of breakpoints. Personally, I use IntelliJ. You can add breakpoints to your code. Breakpoints will make your program halt when they get hit. At that time you can see call stack in Debugger window under IntelliJ.
IntelliJ provides great support for debugging, and also provides easy tutorials to get started with IntelliJ Debugger Tool.

If you want to print Stack Trace, then make use of Thread.currentThread.getStackTrace() function.

Upvotes: 0

Joe
Joe

Reputation: 1342

This is what you want

class Example {
  public void init() {
     func1();
     // TODO : now here I want to print the stack trace that it went from:
     try { throw new Throwable("Debugging") } catch (Throwable t) { t.printStackTrace(); }
     // or
     System.out.println(Arrays.toString(Thread.currentThread().getStackTrace()));
     // func1
     // func2
     // func3
  }
  public void func1() {
     func2();
  }
  public void func2() {
     func3();
  }
  public void func3() {
     // some code here
  }
}

Upvotes: 1

Related Questions