JavaHow to Use StackTraceElement in Java

How to Use StackTraceElement in Java

Using StackTraceElement, Java developers can know the stack trace at any given point in the code flow. Below is a code example showing how to use StackTraceElement in Java:

*/

public class UsingStackTraceElement
{
	public static void main(String args[])
	{
		UsingStackTraceElement usingStackTraceElement = new UsingStackTraceElement();
		usingStackTraceElement.proceed();
	}
	
	public void proceed()
	{
		myMethod();
	}
	
	private void myMethod()
	{
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
		for(StackTraceElement st : stackTrace)  
        {  
            System.out.println(st);  
        }  		
	}
}

/*

If you run this code in your integrated development environment (IDE) or code editor, you get the following output:

[[email protected]]# java UsingStackTraceElement
java.lang.Thread.getStackTrace(Unknown Source)
UsingStackTraceElement.myMethod(UsingStackTraceElement.java:20)
UsingStackTraceElement.proceed(UsingStackTraceElement.java:15)
UsingStackTraceElement.main(UsingStackTraceElement.java:10)

Latest Posts

Related Stories