当正在访问的数组的不存在索引时,将抛出ArrayIndexoutofBoundSexception。
数组是基于零索引的,因此第一个元素的索引为0,最后元素的索引是数组容量减去1(即array.Length 1)。
因此,索引 i对索引元素的任何请求,i必须满足条件0 <= i <array.length,否则将抛出arrayIndexoutofBoundSexception。
以下代码是一个简单的示例,其中抛出了arrayIndexoutofBoundSexception。
String[] people = new String[] { "Carol", "Andy" }; //An array will be created: //people[0]: "Carol" //people[1]: "Andy" //Notice: no item on index 2. Trying to access it triggers the exception: System.out.println(people[2]); //throws an 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]); }
日期:2020-06-02 22:15:20 来源:oir作者:oir