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

更新於:19-2 月 -2020

14K+ 瀏覽量

職業進階

完成教程即可獲得認證

開始
廣告
© . All rights reserved.