在这篇博文中,学习如何修复/处理java.lang.ArrayIndexOutOfBoundsException错误。
什么是java.lang.ArrayIndexOutOfBoundsException错误?
这个异常是java中常见的异常之一。
在项目中,当从数据库中检索数据以及处理数组和数组列表时,Java开发人员常常会遇到这种异常。
ArrayIndexOutOfBoundsException是java.lang包中的一个类,它扩展了IndexOutOfBoundsException,由RuntimeException扩展。IndexOutOfBoundsException是一个运行时异常,在java虚拟机中执行java时发生。运行时异常可能不在方法签名中声明,而在方法签名声明中必须声明,
当访问数组中的无效索引时,即索引值不在0和array.length-1之间的范围
时,Java 会抛出ArrayIndexOutOfBoundsException异常 。
打印java中ArrayIndexOutOfBoundsException错误的堆栈跟踪
线程 "main "中的异常 java.lang.ArrayIndexOutOfBoundsException: -1
下面的java程序代码抛出了ArrayIndexOutOfBoundsException异常
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String\[\] args) {
Integer array\[\] = new Integer\[10\];
System.out.println(" array index 0 value " + array\[0\]);
System.out.println(" array index 10 value " + array\[10\]);
}
}
```Above java code create an Integer array of size 10,
In Java, an array‘s index always start with 0 and the last index is 9 Array with index 0 to 9 has the default values Null(Integer object default value). Accessing an array with an index out of this range (0 -9) throws this exception.
Executing array\[0\] executes fine and outputs null, whereas array\[10\] is invalid and index 10 is invalid, so the java program throws Array Index Exception.
线程 "main "中的异常 java.lang.ArrayIndexOutOfBoundsException。10at
ArrayIndexOutOfBoundsExample.main(ArrayIndexOutOfBoundsExample.java:6)
### How to handle ArrayIndexOutOfBoundsException error in java?
Let us see how to handle/ _solve IndexOutOfBoundsException exception types_ in java
1. _Always check for the expected invalid index in array bounders_
Arrays are fixed in size and always start with index 0. We have to write a conditional check to consider the array elements between 0 to n-1 if the array size is n-1
Possibility fix is to have for loop check for valid ranges.
<pre>
for(int index=0;index<array.length;index++)</pre>
2. _**Fix for Array Index Bounds Exception as well as IndexOutOfBounds Exception for ArrayList**_
ArrayList also has index-based methods like set and get. The Exception throws when ArrayList access elements with the get method before adding the elements/objects into the ArrayList using the set method. So make sure that add below check-in ArrayList or vectors
<pre>if(index >0 || index <= arraylist.size())</pre>