如何处理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