(1)代码实现:

public class ArrayIndexOutOfBoundsException extends Exception {
    public ArrayIndexOutOfBoundsException() {
        super("该元素不存在,已超出数组长度!!!");
    }
}

(2)代码实现:

public class NewTest {
    public static void main(String[] args) {
        int[] arr = {6, 31, 75, 9, 22};
        try {
            if (arr.length < 6) {
                throw new ArrayIndexOutOfBoundsException();
            }
            System.out.println(arr[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
    }
}

运行结果:

该元素不存在,已超出数组长度!!!
``
1自定义一个异常类ArrayIndexOutOfBoundsException当访问一个一维数组超出数组长度时发出警告该元素不存在已超出数组长度!!!。2定义测试类NewTest当访问一维数组63175922的第六个元素时通过自定义异常类ArrayIndexOutOfBoundsException发出警告信息。

原文地址: https://www.cveoy.top/t/topic/dwgm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录