如果我运行以下测试,它将失败:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
出现以下错误:
Expected :stackTraceMentionsTheLocationWhereTheExceptionWasThrown
Actual :setUp
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪只是平坦的说谎.
抛出异常时,为什么不重写堆栈跟踪?我不是Java开发者,也许我在这里遗漏了一些东西.
我e.fillInStacktrace()在创建异常后直接发现了一个显式调用Exception e = new Exception().
我认为这是多余的,因为Throwable已经调用的构造函数fillInStacktrace().
但也许我忽略了一些东西,这条线很有用:
Exception e = new Exception();
e.fillInStackTrace();
creationInfo = new CreationInfo(e.getStackTrace());
Run Code Online (Sandbox Code Playgroud)
(public CreationInfo(StackTraceElement[] aStackTrace){...})
我认为
e.fillInStackTrace();在创建异常之后直接额外调用是多余的并且会浪费大量资源,因为这种方法很昂贵.
它接缝这个构造只需要获取当前的栈跟踪,因此:
creationInfo = Thread.currentThread().getStackTrace();
Run Code Online (Sandbox Code Playgroud)
是更好的方法.
在填写问题报告之前,我想问你是否忽略了一些问题?
在Java 7中增加了Rethrow Exception功能.我知道它的概念,但我想看到它的真实应用以及为什么需要这个功能?