说明
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;
}
}
}