Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Events 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?

like image 327
theomega Avatar asked Mar 03 '26 00:03

theomega


2 Answers

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.

like image 120
T.J. Crowder Avatar answered Mar 04 '26 21:03

T.J. Crowder


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.

like image 39
Beska Avatar answered Mar 04 '26 20:03

Beska



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!