Java Throwable fillInStackTrace()方法

java.lang.Throwable.fillInStackTrace() 方法填充在执行堆栈跟踪。此方法记录该Throwable对象信息内有关当前线程的堆栈帧的当前状态。

1 语法

public Throwable fillInStackTrace()

2 参数

3 返回值

该方法返回一个引用该Throwable的实例。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Throwable fillInStackTrace()方法
 */
import java.lang.*;

public class ThrowableDemo {

  public static void function1() throws Exception {
     throw new Exception("this is thrown from function1()");
  }

  public static void function2() throws Throwable {
    try {
       function1();
    } 
    catch(Exception e) {
       System.err.println("Inside function2():");
       e.printStackTrace();
       throw e.fillInStackTrace();
    }
  }

  public static void main(String[] args) throws Throwable {
    try {
       function2();
    }
    catch (Exception e) {
       System.err.println("Caught Inside Main:");
       e.printStackTrace();
    }
  }
}

输出结果为:

Inside function2():
java.lang.Exception: this is thrown from function1()
at ThrowableDemo.function1(ThrowableDemo.java:4)
at ThrowableDemo.function2(ThrowableDemo.java:9)
at ThrowableDemo.main(ThrowableDemo.java:19)
Caught Inside Main:
java.lang.Exception: this is thrown from function1()
at ThrowableDemo.function2(ThrowableDemo.java:13)
at ThrowableDemo.main(ThrowableDemo.java:19)

 

热门文章

优秀文章