开发者

Why does Throwable.getMessage() occasionally return null?

开发者 https://www.devze.com 2023-03-16 07:46 出处:网络
I have a method that sometimes throws an exception: this.items[index] = element; And I have a unit test that asserts that the exception that ought to be thrown is actually thrown:

I have a method that sometimes throws an exception:

this.items[index] = element;

And I have a unit test that asserts that the exception that ought to be thrown is actually thrown:

try
{
    doSomethingWithIndex(-1);
    Assert.fail("should cause exce开发者_运维知识库ption");
}
catch (IndexOutOfBoundsException expected)
{
    Assert.assertNotNull(expected.getMessage());
}

This test runs as part of the continuous build and sometimes, occasionally it fails because getMessage() in fact returns null. Why would this happen? My code can never throw an exception with a null message.

EDIT

My original code example was misleading, the thrown exception is actually coming from directly indexing an array. I can reproduce the same behavior with a custom thrown exception though.

I added the suggested code:

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

The console output is missing the stack trace in addition to the cause. Here's the full output:

java.lang.ArrayIndexOutOfBoundsException


Found the answer on a similar question.

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

The JVM flag -XX:-OmitStackTraceInFastThrow prevents this behavior and seems to fix the flickering unit tests.


Try printing stack trace of exception when it has null message. It's possible that some other code throws it. Like you actually accessing past array length.


You wrote that: "My code can never throw an exception with a null message"

Are you yousing any 3rd party library? I assume standard java codes never throw exceptions like this above, but some pourly coded jar... :)

0

精彩评论

暂无评论...
验证码 换一张
取 消