`
静静的小谱
  • 浏览: 19297 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
最近访客 更多访客>>
社区版块
存档分类
最新评论

异常和异常处理

    博客分类:
  • java
阅读更多
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");
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics