如何处理Java数组索引越界异常?
一般而言,数组是固定大小,使用索引访问每个元素。例如,我们创建了一个大小为 9 的数组。访问该数组的元素的有效表达式将是 a[0] 到 a[8](长度 - 1)。
每当您使用 -ve 值或大于或等于数组大小的值时,就会抛出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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP