首页 文章资讯内容详情

Java异常处理中的嵌套try块

2026-06-04 1 花语

顾名思义,try块中的try块在Java中称为嵌套try块。当不同的块(例如外部和内部)可能导致不同的错误时,就需要这样做。要处理它们,我们需要嵌套的try块。

现在让我们看一个实现嵌套try块的示例-

示例

class Main { // main method public static void main(String args[]) { try { int a[]=new int[10]; //显示索引12处的元素 System.out.println(a[12]); // another try block try { System.out.println("相除"); int res = 100/ 0; } catch (ArithmeticException ex2) { System.out.println("抱歉的!。 被零除是不可行的!"); } } catch (ArrayIndexOutOfBoundsException ex1) { System.out.println("ArrayIndexOutOfBoundsException"); } } }

输出结果

ArrayIndexOutOfBoundsException

现在我们将在上面的示例中进行一些更改-

示例

class Main { // main method public static void main(String args[]) { try { int a[] = {30, 45, 60, 75, 90, 105, 120, 140, 160, 200}; //显示索引8处的元素 System.out.println("显示索引8处的元素 = "+a[8]); // another try block try { System.out.println("相除"); int res = 100/ 0; } catch (ArithmeticException ex2) { System.out.println("抱歉的!被零除是不可行的!"); } } catch (ArrayIndexOutOfBoundsException ex1) { System.out.println("ArrayIndexOutOfBoundsException"); } } }

输出结果

显示索引8处的元素 = 160 Division 抱歉的!被零除是不可行的!