Java.lang.Throwable 类

java.lang.Throwable.printStackTrace() 方法用于将此 throwable 及其回溯打印到指定的PrintWriter.

语法

public void printStackTrace(PrintWriter s) 

参数

s指定用于输出的PrintWriter

返回值

无。

异常

无。

示例:

下面的示例演示如何使用 java.lang.Throwable.printStackTrace() 方法。

import java.lang.*;
import java.io.*;

public class MyClass {
  public static void main(String[] args) throws Throwable {
    try{
      int x = 10, y = 0, z;
      z = x/y;
      System.out.println(z);
    }
    catch (Exception e){
      //使用StringWriter进行转换
      //跟踪到字符串
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);  
      
      //打印这个 throwable 及其回溯到 pw
      e.printStackTrace(pw);

      String error = sw.toString();
      System.out.println("Error is:\n" + error); 
    }
  }
} 

上述代码的输出将是:

Error is:
java.lang.ArithmeticException: / by zero
  at MyClass.main(MyClass.java:8) 

示例:

再考虑一个示例以更好地理解这一概念。

import java.lang.*;
import java.io.*;

public class MyClass {
  public static void main(String[] args){
    OutputStream out;
    try{
      testException();
    }
    catch (Exception e){
      //使用StringWriter进行转换
      //跟踪到字符串
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);  
      
      //打印这个 throwable 及其回溯到 pw
      e.printStackTrace(pw);

      String error = sw.toString();
      System.out.println("Error is:\n" + error); 
    }
  }

  //抛出异常的方法
  public static void testException() throws Exception { 
    throw new Exception("New Exception Thrown"); 
  } 
} 

上述代码的输出将是:

Error is:
java.lang.Exception: New Exception Thrown
  at MyClass.testException(MyClass.java:26)
  at MyClass.main(MyClass.java:8)