异常和异常处理


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");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值