Throwable.fillInStackTrace本是一个 synchronized native 方法,其如下:
/**
* Fills in the execution stack trace. This method records within this
* <code>Throwable</code> object information about the current state of
* the stack frames for the current thread.
*
* 在 Throwable 对象中 填充 执行堆栈信息。此方法在 Throwable 对象中 记录 当前线程的栈帧的 当前状态信息
*
* @return a reference to this <code>Throwable</code> instance.
* @see java.lang.Throwable#printStackTrace()
*/
public synchronized native Throwable fillInStackTrace();
当抛出此异常时,就会通过这个方法填充当前线程的栈帧信息。如果,我们重新了此方法(native实现是将线程的栈帧信息记录到此 Throwable 对象中),不记录当前线程的栈帧信息,那么,当此异常被抛出时,就无法保存堆栈信息了
测试代码如下:
package marvin.doit.exception_cause_low_performance;
public class JustForDemoException extends RuntimeException {
private static final long serialVersionUID = 2134186859756705446L;
@Override
public Throwable fillInStackTrace() {
return this;
}
private static void method1() {
System.out.println("in method 1");
method2();
}
private static void method2() {
System.out.println("in method 2");
method3();
}
private static void method3() {
System.out.println("in method 3");
method4();
}
private static void method4() {
System.out.println("in method 4");
throw new JustForDemoException();
}
public static void main(String[] args) {
method1();
}
}
注意:上面代码中,我们覆写了 fillInStackTrace(),执行后,我们得到如下结果:
不要覆写(就想我们平时作的那样,平时谁会去覆写这个方法啊)。一切正常,我们又看到了常见的 堆栈信息