[英]Why does a ArrayIndexOutOfBoundsException happen here?
I got the following code in my Android-App: 我的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
. retrieveEvents()从Internet获取一些Event
,所以这可能会失败但是为空或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. 用户可以选择要显示的Event
,以避免异常我使用模运算来确保eventNr
在边界内。 This works fine on any devices I tested on BUT: 这适用于我在BUT上测试的任何设备:
I get error-reports from other users where the second last line (the array-access) throws an ArrayIndexOutOfBoundsException
. 我收到来自其他用户的错误报告,其中第二行(数组访问)抛出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? 请记住: retrieveEvents()
和getFromUserInput()
函数都可以返回无效数据,但我想我检查了每个案例,那么我的getFromUserInput()
?
Have you ensured that eventNr
is never negative? 你确定eventNr
永远不会消极吗? 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. 问题在于,例如,如果eventNr
为-1
且events.length
为5,则-1 % 5 = -1
,当然events[-1]
超出范围。
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? retrieveEvents()是否可能始终返回对同一数组的引用,但是实时修改了数组? If so, that could be your issue. 如果是这样,那可能是你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.