Java.lang.Throwable.printStackTrace() 方法
描述
java.lang.Throwable.printStackTrace(PrintStream s) 方法将此 throwable 及其回溯打印到指定的打印流。
声明
以下是 java.lang.Throwable.printStackTrace() 方法的声明。
public void printStackTrace(PrintStream s)
参数
s − 这是用于输出的 PrintStream
返回值
此方法不返回任何值。
异常
NA
示例
下面的例子展示了 java.lang.Throwable.printStackTrace() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class ThrowableDemo {
public static void main(String[] args) throws Throwable {
OutputStream out;
try {
ExceptionFunc();
} catch(Throwable e) {
out = new FileOutputStream("file.text");
// prints this throwable and its backtrace to the print stream
PrintStream ps = new PrintStream(out);
e.printStackTrace(ps);
}
}
public static void ExceptionFunc() throws Throwable {
Throwable t = new Throwable("This is new Exception...");
StackTraceElement[] trace = new StackTraceElement[] {
new StackTraceElement("ClassName","methodName","fileName",10)
};
// sets the stack trace elements
t.setStackTrace(trace);
throw t;
}
}
假设我们有一个文本文件 file.txt,它作为示例程序的输出生成。文件内容包括 −
java.lang.Throwable: This is new Exception... at ClassName.methodName(fileName:10)

