【发布时间】:2010-12-14 09:11:49
【问题描述】:
如果我运行以下测试,它会失败:
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 开发人员,也许我在这里遗漏了一些东西。
【问题讨论】:
-
我不知道 6 年前我们是否可以设置异常的堆栈跟踪“原因”,但最好在创建新异常之后并在抛出它之前使用它:Exception.initCause(Throwable ),您可以在其中使用 setStackTrace() 配置原因堆栈跟踪。