在try,catch,finally中return,throw覆盖的问题总结

先给出一段代码,请大家思考一下这段代码的输出。
class T{
	public static void main(String[] args) {
		try {
			if (testEx()) {
				System.out.println("程序正常o^o");
			}else{
				System.out.println("程序异常T_T");
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("发生除零异常啦~~~~");
		}
	}
	public static boolean testEx(){
		boolean ok=true;
		try {
			int i=3/0;
			return false;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("发生除零异常");
			throw e;
		}finally {
			return ok;
		}
	}
}

你的答案是否是:

发生除零异常

发生除零异常啦~~~~

那么恭喜你,答错啦~~~

正确的答案应该是:

发生除零异常

程序正常o^o

为什么会这样呢?我们知道在java中,无论是return还是抛出异常,都会导致方法的结束。但是java中finally语句又必须执行,所以finally语句的执行时机应该是在try语句中的return语句之前,或者catch语句中throw语句执行之前。不然,无论是return语句执行,还是throw语句执行,都将导致finally语句无法得到执行。又由于在finally语句中,书写了return语句,就是这么个return语句,将导致方法的提前结束,因而无论是try中的return语句,还是catch中的throw语句,都将失去执行的机会,仿佛被覆盖掉了一般。因此有了以上的结果。



你可能感兴趣的:(在try,catch,finally中return,throw覆盖的问题总结)