1自定义一个异常类ArrayIndexOutOfBoundsException当访问一个一维数组超出数组长度时发出警告该元素不存在已超出数组长度!!!。
代码实现:
public class ArrayIndexOutOfBoundsException extends Exception {
public ArrayIndexOutOfBoundsException() {
super("该元素不存在,已超出数组长度!!!");
}
}
使用方法:
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
输出结果:
该元素不存在,已超出数组长度!!!
原文地址: https://www.cveoy.top/t/topic/dwx4 著作权归作者所有。请勿转载和采集!