Java异常处理:哪个catch块会捕获ArrayIndexOutOfBoundsException?

您提供的Java代码如下:javapublic 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.'); } }}

分析:

  1. 问题代码: System.out.println(numbers[6]); 试图访问数组 numbers 中不存在的索引 6,而数组只有索引 0 到 2,因此会抛出 ArrayIndexOutOfBoundsException 异常。

  2. 异常捕获: catch (ArrayIndexOutOfBoundsException e) 会捕获到这个异常,因为它是专门处理 ArrayIndexOutOfBoundsException 类型的异常。

  3. 输出结果: 程序会输出以下两行:

    • 'Array index out of bounds.' (来自捕获到异常的 catch 块) - 'Finally block executed.' (来自 finally 块,无论是否捕获到异常,它都会执行)

总结:

这段代码演示了Java中的异常处理机制,try-catch 块用于捕获和处理异常,finally 块用于执行无论是否发生异常都需要执行的代码。

Java异常处理:哪个catch块会捕获ArrayIndexOutOfBoundsException?

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

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