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