gpt4 book ai didi

java - 为什么 Throwable.getMessage() 偶尔会返回 null?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:17:56 28 4
gpt4 key购买 nike

我有一个有时会抛出异常的方法:

this.items[index] = element;

我有一个单元测试断言应该抛出的异常实际上被抛出了:

try
{
doSomethingWithIndex(-1);
Assert.fail("should cause exception");
}
catch (IndexOutOfBoundsException expected)
{
Assert.assertNotNull(expected.getMessage());
}

此测试作为持续构建的一部分运行,有时会失败,因为 getMessage() 实际上返回 null。为什么会这样?我的代码永远不会抛出空消息异常。

编辑

我的原始代码示例具有误导性,抛出的异常实际上来自直接索引数组。不过,我可以使用自定义抛出的异常重现相同的行为。

我添加了建议的代码:

catch (IndexOutOfBoundsException expected)
{
if (expected.getMessage() == null)
{
expected.printStackTrace();
}
Assert.assertNotNull(expected.getMessage());
}

除了原因之外,控制台输出还缺少堆栈跟踪。这是完整的输出:

java.lang.ArrayIndexOutOfBoundsException

最佳答案

similar question 上找到了答案.

The JIT compiler will optimize away stack traces in certain exceptions if they happen enough.

JVM 标志 -XX:-OmitStackTraceInFastThrow 可以防止这种行为,并且似乎可以修复闪烁的单元测试。

关于java - 为什么 Throwable.getMessage() 偶尔会返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6538792/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com