嵌套的Try-Catch块--------异常处理(3)

本文深入探讨了Java中异常处理的机制,通过一个包含嵌套try-catch块的示例代码,展示了如何在不同层级捕获并处理异常。具体分析了当一个try块没有对应异常可处理时,其父类的异常处理机制如何介入,以及最终javaruntime系统如何处理未能被任何catch块捕获的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当有一个Try块没有一个对应的异常可处理,则其父类的异常处理机制去处理。如果父类的异常处理机制不能处理,则java run-time system将会抛出一个异常。

例子:

class Nest{
   public static void main(String args[]){
	 //Parent try block
     try{
    	//Child try block1
         try{
            System.out.println("Inside block1");
            int b =45/0;
            System.out.println(b);
         }
         catch(ArithmeticException e1){
            System.out.println("Exception: e1");
         }
         //Child try block2
         try{
            System.out.println("Inside block2");
            int b =45/0;
            System.out.println(b);
         }
         catch(ArrayIndexOutOfBoundsException e2){
            System.out.println("Exception: e2");
         }
        System.out.println("Just other statement");
    }
    catch(ArithmeticException e3){
    	 System.out.println("Arithmetic Exception");
         System.out.println("Inside parent try catch block");
    }
    catch(ArrayIndexOutOfBoundsException e4){
    	System.out.println("ArrayIndexOutOfBoundsException");
         System.out.println("Inside parent try catch block");
    }
    catch(Exception e5){
    	System.out.println("Exception");
         System.out.println("Inside parent try catch block");
     }
     System.out.println("Next statement..");
  }
}
输出:
Inside block1
Exception: e1
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..


转载于:https://www.cnblogs.com/yandufeng/p/5009626.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值