當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java 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)

相關用法


注:本文由純淨天空篩選整理自 Java.lang.Throwable.printStackTrace() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。