Tij12_异常:while实现恢复模型

说明

java的异常处理默认是中断模型,即当异常发生时中断当前执行,跳转到异常处理机制。
部分场景下,恢复模型也需要,如检查入参直到允许执行。
以下是例子。
关键点是:异常处理要在while内。

package org.example.baseTec;

public class CRecoveryModel {
    public static void main(String[] args) {

        int[] arr={1,2,3,4};
        int i=10;

        System.out.println("1========================");
        for (  i=10  ; i >= 0; i--) {
            while (true) {
                try {
                    System.out.println(arr[i]);  //step1.执行,抛出异常
                                                 //step2.中断原程序,跳转到
                    break;                       //超脚标的情况下,该行不会执行
                                                 //step5.脚标正常后,打印1个后,退出while循环块
                }catch (Exception e) {
                    e.printStackTrace();         //step3.执行
                    break;                       //step4.跳出while循环块
                }
            }

        }
        System.out.println("2========================");
        i=10;

        while (true) {                                                    //while+i--,就可以执行for循环,没必要再加for了
            try {
                System.out.println(arr[i]);
            } catch (Exception e) {
                System.out.println("exception catched:"+e.getMessage());  //catch中断的是监控区,整体程序还在执行
            }
            i--;
            if(i<0) break;
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值