What is the thread getStackTrace() function in Java?

The getStackTrace() method

The getStackTrace() method is used to return the array regarding stack trace elements. These elements represent the stack dump related to the thread.

How does getStackTrace() work?

  • If this thread has been dismissed or has not started, then the method will return an array of zero-length.

  • If a non-zero array is returned, then the first element of that array shows the top of the stack.

  • getStackTrace() is the most recent method of invocation in the series. The bottom of the stack is represented by the last element of an array.

  • getStackTrace() is the least recent method of invocation in the series.

Syntax


StackTraceElement[ ] getStackTrace( )

Parameters

getStackTrace does not take any parameters.

Return value

The function returns the array regarding StackTraceElement, and every element shows a single stack frame.

SecurityException

The checkPermission method occurs when a security manager exists. This method does not permit getting the stack trace of the thread.

Code

The code below demonstrates how to use the getStackTrace() function.

// Load library
import java.lang.Thread;
// Main class
public class Test_thread{
// main method
public static void main(String[] args) {
function();
}
public static void function() {
new Test_thread().function2();
}
public void function2() {
System.out.println(Thread.currentThread().getStackTrace()[3].getClassName());
}
}

Free Resources