Reputation: 26738
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
Upvotes: 9
Views: 5706
Reputation: 26738
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.
Upvotes: 9
Reputation: 14651
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... :)
Upvotes: 0
Reputation: 24732
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.
Upvotes: 1