Java Throwable printStackTrace()方法

java.lang.Throwable.printStackTrace(PrintStream s) 方法打印此抛出其回溯到指定的打印流。

1 语法

public void printStackTrace(PrintStream s)

2 参数

s : 这是用于输出所述的PrintStream

3 返回值

此方法不返回任何值。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Throwable printStackTrace()方法
 */
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)

 

热门文章

优秀文章