Java Thread getStackTrace Example


 

Java Thread getStackTrace Example

This section explains use of getStackTrace() method in java Thread.

This section explains use of getStackTrace() method in java Thread.

Java Thread getStackTrace Example

This section explains use of getStackTrace() method  in java Thread.

Thread getStackTrace() :

It returns an array of StackTraceElement, and individual of them shows one stack frame. acts as the stack dump of the given thread. This method provides the array of stack trace elements which can access to the stack trace information. Stack dump of thethread is represented by the stack trace elements. If thread is not presented then this method will return no element in array that is zero length array. If length is non zero then the element at zero position represents
the top of the stack,and this represent last method invocation of the sequence. In this point you can create throwable and thrown. The last array element shows the stack bottom and it is the first method invocation in the sequence.
It throws SecurityException exception.

Example :  In this example we are throwing exception by using getStackTrace() method.

public class GetStackTrace {
	public static void main(String args[]) {
		try {
			NewException();
		} catch (Throwable e) {
			/* Gets the stack trace. */
			StackTraceElement[] trace = e.getStackTrace();
			System.err.println("" + trace[0].toString());
		}
	}

	public static void NewException() throws Throwable {
		Throwable throwable = new Throwable("New Exception...");
		StackTraceElement[] element = new StackTraceElement[] { new StackTraceElement(
				"GetStackTrace", "NewException", "Roseondia", 10) };
		/* Sets the stack trace elements that will be returned */
		
		throwable.setStackTrace(element);
		throw throwable;
	}
}

Output :

GetStackTrace.NewException(Roseondia:10)

Ads