-2

-1从我的response. 我得到了这个异常,如何处理这个异常,这样我就可以避免任何与我的Array.

Constants.Friends[Integer.parseInt(custom.getFriendsList())]

例如,如果我的数组包含四个项目。

String[] MyList = {"One","Two","Three","Four"};

如果我得到 -1 或任何大于 3 的值,我该如何处理它们。

4

2 回答 2

7

ArrayIndexOutOfBoundsException是一个未经检查的异常,这意味着它通常表示编程错误,而不是程序控制之外的条件。这些异常应该被阻止,而不是被处理。

在这个特定实例中,您应该在将值作为索引传递给数组之前检查该值,如下所示:

int pos = Integer.parseInt(custom.getFriendsList());
if (pos < 0 || pos >= Constants.Friends.length) {
    // Handle the error and exit or re-read the pos
}
// Accessing Friends[pos] is safe now:
String friend = Constants.Friends[pos];
于 2013-05-09T17:18:40.957 回答
1
int index = Integer.parseInt(custom.getFriendsList());
if (index < 0 || index > list.length)
{
    //notify user that input is invalid retry getting input
}
else
{
    return list[index];
}

这应该可以解决问题;因为我不知道索引无效时会发生什么,所以我将其保持打开状态。

于 2013-05-09T17:19:16.443 回答