Java 异常处理:ArrayIndexOutOfBoundsException 捕获与输出
以下 Java 代码展示了如何捕获并处理 ArrayIndexOutOfBoundsException 异常:
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[6]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println('Array index out of bounds.');
} catch (Exception e) {
System.out.println('Exception occurred.');
} finally {
System.out.println('Finally block executed.');
}
}
}
这段代码中,异常将被第一个 catch 块捕获,即 catch (ArrayIndexOutOfBoundsException e)。这是因为在 try 块中,我们尝试访问索引为 6 的数组元素,而实际上数组只有长度为 3,所以会抛出一个 ArrayIndexOutOfBoundsException 异常。
由于 ArrayIndexOutOfBoundsException 是 Exception 的子类,所以它应该在 catch 块中首先被捕获。
当异常被捕获时,第一个 catch 块将执行,并输出 'Array index out of bounds.' 字符串。
在捕获异常后,程序将继续执行 finally 块中的代码。
因此,运行这段代码将会输出:
Array index out of bounds.
Finally block executed.
原文地址: https://www.cveoy.top/t/topic/pSI 著作权归作者所有。请勿转载和采集!