Java ArrayIndexOutOfBoundsException异常

示例

在ArrayIndexOutOfBoundsException当正在访问一个不存在的一个数组的索引被抛出。

数组是从零开始的索引,因此第一个元素0的索引为,最后一个元素的索引为数组容量减去1(即array.length - 1)。

因此,索引对数组元素的任何请求i都必须满足该条件  0 <= i < array.length,否则将抛出ArrayIndexOutOfBoundsException。


以下代码ArrayIndexOutOfBoundsException是抛出an的简单示例。

String[] people = new String[] { "Carol", "Andy" };

// 将创建一个数组:
// people[0]: "Carol"
// people[1]: "Andy"

// 注意:索引2上没有任何项目。尝试访问它会触发异常:
System.out.println(people[2]);  // 抛出ArrayIndexOutOfBoundsException。

输出:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at your.package.path.method(YourClass.java:15)

请注意,异常中还包含正在访问的非法索引(2在示例中);此信息可能有助于查找异常原因。


为了避免这种情况,只需检查索引是否在数组的范围内:

int index = 2;
if (index >= 0 && index < people.length) {
    System.out.println(people[index]);
}