Home » Java programming language

Java Throwable getStackTrace() Method with Example

Throwable Class getStackTrace() method: Here, we are going to learn about the getStackTrace() method of Throwable Class with its syntax and example.
Submitted by Preeti Jain, on January 06, 2020

Throwable Class getStackTrace() method

  • getStackTrace() Method is available in java.lang package.
  • getStackTrace() Method is used to return an array of StackTraceElement and every element in an array denotes one stack frame.
  • As we know that the first element of the array denotes the top of the stack and the last element of the array denotes bottom of the stack (i.e. In a sequence the last method called to represent the top of the stack and in a sequence the first method called represents the bottom of the stack).
  • getStackTrace() Method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • getStackTrace() Method does not throw an exception at the time of maintaining method calls onto a stack.

Syntax:

    public StackTraceElement[] getStackTrace();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is StackTraceElement[], it returns an array of stack trace elements denoting the tracing of method calls onto a stack.

Example:

// Java program to demonstrate the example // of StackTraceElement method of Throwable public class GetStackTrace { public static void main(String args[]) { try { stackTraceMethod(); } catch (Throwable ex) { // By using getStackTrace() method is to get the // stack trace element StackTraceElement[] st_tr = ex.getStackTrace(); System.err.println("st_tr[0].toString()" + st_tr[0].toString()); } } public static void stackTraceMethod() throws Throwable { int li_nu = 7; // instantiate a new exception called // Throwable Throwable th = new Throwable("Raise New Exception"); StackTraceElement[] st_tr = new StackTraceElement[] { new StackTraceElement("cl_na", "me_na", "fu_na", li_nu) }; // By using setStackTrace() method is to set // the elements in stack th.setStackTrace(st_tr); throw th; } }

Output

st_tr[0].toString()cl_na.me_na(fu_na:7)
Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.