如何在 Java 中捕獲超出陣列索引範圍的異常?
當你嘗試訪問超出範圍的陣列元素時,將會引發 ArrayIndexOutOfBoundsException 異常。
示例
public class ArrayIndexOutOfBounds {
public static void main(String args[]) {
try {
int[] a = new int[]{1,2,3,4,5};
int x = 6;
a[10] = x;
} catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Array size is restricted to 5 elements only");
}
}
}輸出
Array size is restricted to 5 elements only
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP