以下Java代码演示了如何使用try-catch块捕获和处理ArrayIndexOutOfBoundsException异常:

public class Main {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // 尝试访问索引为5的数组元素,但数组只有3个元素
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println('Array index out of bounds.'); // 捕获异常并输出错误信息
        }
    }
}

在这段代码中,try块中的异常将被捕获。因为我们在try块中尝试访问索引为5的数组元素,而实际上数组只有长度为3,所以会抛出一个ArrayIndexOutOfBoundsException异常。

当异常被捕获时,catch块将会执行,并输出'Array index out of bounds.'字符串。这是我们在catch块中指定的代码。

因此,运行这段代码将会输出:'Array index out of bounds.'

Java ArrayIndexOutOfBoundsException: 捕获并处理数组越界异常

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

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