Throwable类getStackTrace()方法 (Throwable Class getStackTrace() method)
getStackTrace() Method is available in java.lang package.
getStackTrace()方法在java.lang包中可用。
getStackTrace() Method is used to return an array of StackTraceElement and every element in an array denotes one stack frame.
getStackTrace()方法用于返回一个StackTraceElement数组,并且数组中的每个元素都表示一个堆栈帧。
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()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
getStackTrace() Method does not throw an exception at the time of maintaining method calls onto a stack.
在将方法调用维护到堆栈上时, getStackTrace()方法不会引发异常。
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.
方法的返回类型为StackTraceElement [] ,它返回一个堆栈跟踪元素数组,表示对堆栈的方法调用的跟踪。
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)
翻译自: https://www.includehelp.com/java/throwable-getstacktrace-method-with-example.aspx