public class ExceptionRecover {
public static void main(String[] args) {
openDoor();
String food = null; // 注意变量作用域, 如果定义在 try / catch 块内, 则无法被函数内其他作用域使用
try {
food = cook();
} catch (RuntimeException e) { // catch 块中的内容是备用方案
// 如果程序没有备用方案, 那么就不要 catch
e.printStackTrace();
// System.out.println("I'm hungry, but there is no food");
food = "express noodles"; // 提供备用方案
}
eat(food);
try {
eat(cook());
} catch (RuntimeException e) { // 如果要给出备用方案, 一定要准确
// 如果此时因为 eat 抛出异常而结束, 则 catch 块仍可能抛出异常
eat("express noodles");
}
rest();
}
public static void openDoor() {
System.out.println("open the door");
}
public static String cook() {
System.out.println("cook dinner");
throw new RuntimeException("rice is bad");
// return "rice and meat";
}
public static void eat(String food) {
System.out.println("eat " + food);
// throw new RuntimeException("dump");
}
public static void rest() {
System.out.println("rest");
}
}