Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Throwable.getMessage() occasionally return null?

Tags:

java

exception

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 exception");
}
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
like image 460
Craig P. Motlin Avatar asked Jun 30 '11 17:06

Craig P. Motlin


2 Answers

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.

like image 90
Craig P. Motlin Avatar answered Oct 01 '22 17:10

Craig P. Motlin


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.

like image 21
Alex Gitelman Avatar answered Oct 01 '22 19:10

Alex Gitelman