如果我运行以下测试,它将失败:
public class CrazyExceptions {
private Exception exception;
@Before
public void setUp(){
exception = new Exception();
}
@Test
public void stackTraceMentionsTheLocationWhereTheExceptionWasThrown(){
String thisMethod = new Exception().getStackTrace()[0].getMethodName();
try {
throw exception;
}
catch(Exception e) {
assertEquals(thisMethod, e.getStackTrace()[0].getMethodName());
}
}
}
出现以下错误:
Expected :stackTraceMentionsTheLocationWhereTheExceptionWasThrown
Actual :setUp
堆栈跟踪只是平躺。
引发异常时,为什么不重写堆栈跟踪?我不是Java开发人员,也许我在这里错过了一些东西。
堆栈跟踪是在实例化异常时创建的,而不是在引发异常时创建的。这是Java语言规范的指定行为
20.22.1 public Throwable()
This constructor initializes a newly created Throwable object with null as
its error message string. Also, the method fillInStackTrace (§20.22.5) is
called for this object.
....
20.22.5 public Throwable fillInStackTrace()
This method records within this Throwable object information about the
current state of the stack frames for the current thread.
我不知道他们为什么这样做,但是如果规范如此定义,那么它在所有各种Java VM上至少是一致的。
但是,您可以通过exception.fillInStackTrace()
手动调用来刷新它。
另请注意,您应该使用Thread.currentThread().getStackTrace()
而不是使用new Exception().getStackTrace()
(不良样式)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句