如何处理 Java 数组超出边界异常?
一般来说,数组是固定大小的,每个元素都使用索引进行访问。例如,我们创建一个大小为 9 的数组。然后访问该数组元素的有效表达式将为 a[0] 至 a[8](长度-1)。
每当您使用的值小于 0 或者大于或等于数组大小时,就会抛出ArrayIndexOutOfBoundsException。
例如,如果你执行以下代码,它将显示数组中的元素,并提示你提供要选择的元素的索引。由于数组的大小是 7,所以有效的索引将是 0 到 6。
示例
import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
public static void main(String args[]) {
int[] myArray = {897, 56, 78, 90, 12, 123, 75};
System.out.println("Elements in the array are:: ");
System.out.println(Arrays.toString(myArray));
Scanner sc = new Scanner(System.in);
System.out.println("Enter the index of the required element ::");
int element = sc.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
}
}但是,如果你观察一下下面的输出,我们请求了索引为 9 的元素,由于它是一个无效索引,所以会引发一个ArrayIndexOutOfBoundsException,并且执行会终止。
输出
Elements in the array are:: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element :: 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at AIOBSample.main(AIOBSample.java:12)
处理异常
你可以使用如下所示的 try catch 来处理这个异常。
示例
import java.util.Arrays;
import java.util.Scanner;
public class AIOBSampleHandled {
public static void main(String args[]) {
int[] myArray = {897, 56, 78, 90, 12, 123, 75};
System.out.println("Elements in the array are:: ");
System.out.println(Arrays.toString(myArray));
Scanner sc = new Scanner(System.in);
System.out.println("Enter the index of the required element ::");
try {
int element = sc.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 6");
}
}
}输出
Elements in the array are:: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element :: 7 The index you have entered is invalid Please enter an index number between 0 and 6
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP