Java异常处理:哪个catch块会捕获ArrayIndexOutOfBoundsException?
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.'); } }}
分析:
-
问题代码:
System.out.println(numbers[6]);试图访问数组numbers中不存在的索引 6,而数组只有索引 0 到 2,因此会抛出ArrayIndexOutOfBoundsException异常。 -
异常捕获:
catch (ArrayIndexOutOfBoundsException e)会捕获到这个异常,因为它是专门处理ArrayIndexOutOfBoundsException类型的异常。 -
输出结果: 程序会输出以下两行:
- 'Array index out of bounds.' (来自捕获到异常的
catch块) - 'Finally block executed.' (来自finally块,无论是否捕获到异常,它都会执行)
- 'Array index out of bounds.' (来自捕获到异常的
总结:
这段代码演示了Java中的异常处理机制,try-catch 块用于捕获和处理异常,finally 块用于执行无论是否发生异常都需要执行的代码。
原文地址: https://www.cveoy.top/t/topic/pXx 著作权归作者所有。请勿转载和采集!