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