如何在 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