简体   繁体   中英

Why does a ArrayIndexOutOfBoundsException happen here?

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 fail 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM