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


Java Java.lang.Throwable.printStackTrace()用法及代碼示例


描述

這個java.lang.Throwable.printStackTrace() 方法將這個 throwable 及其回溯打印到標準錯誤流。它在錯誤輸出流上打印此 Throwable 對象的堆棧跟蹤,這是字段 System.err 的值。

聲明

以下是聲明java.lang.Throwable.printStackTrace()方法

public void printStackTrace()

參數

NA

返回值

此方法不返回任何值。

異常

NA

示例

下麵的例子展示了 java.lang.Throwable.printStackTrace() 方法的用法。

package com.tutorialspoint;

import java.lang.*;

public class ThrowableDemo {

   public static void main(String[] args) {

      try {
         ExceptionFunc();
      } catch(Throwable e) {
         // prints stacktace for this Throwable Object
         e.printStackTrace();
      }
   }
  
   public static void ExceptionFunc() throws Throwable {

      Throwable t = new Throwable("This is new Exception...");
      StackTraceElement[] trace = new StackTraceElement[] {
         new StackTraceElement("ClassName","methodName","fileName",5)
      };

      // sets the stack trace elements
      t.setStackTrace(trace);
      throw t;
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果——

java.lang.Throwable:This is new Exception...
at ClassName.methodName(fileName:5)

相關用法


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