I got the following code in my Android-App:
Event[] events = retrieveEvents();
if (events != null && events.length>0) {
int eventNr = getFromUserInput();
eventNr = eventNr % events.length;
Event event = events[eventNr];
}
retrieveEvents() gets some Event
s from the Internet, so this can fa开发者_运维知识库il an though be empty or null
. The user can select which Event
to display, to avoid a Exception I use the modulo operation to ensure the eventNr
is within bounds. This works fine on any devices I tested on BUT:
I get error-reports from other users where the second last line (the array-access) throws an ArrayIndexOutOfBoundsException
. How can this happen? What condition have I left unchecked? Where is my error?
Remember: The retrieveEvents()
and the getFromUserInput()
function can both return invalid data, but I think I checked every case, so where is my fault?
Have you ensured that eventNr
is never negative? The check isn't in your quoted code. The problem being that if, for instance, eventNr
is -1
and events.length
is 5, -1 % 5 = -1
and of course events[-1]
is out of bounds.
Is this a threaded application? Is it possible that retrieveEvents() is always returning a reference to the same array, but that the array is being modified in real time? If so, that could be your issue.
精彩评论