在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语句,都将失去执行的机会,仿佛被覆盖掉了一般。因此有了以上的结果。



Java,我们可以在trycatchfinally分别进行returnthrow异常。下面是一些示例代码: 1. 在try进行return: ``` public static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { System.out.println("除数不能为0"); } finally { System.out.println("执行finally块"); } return -1; // 这里的返回值不会被执行,因为在try已经return了 } ``` 2. 在catch进行return: ``` public static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { System.out.println("除数不能为0"); return -1; } finally { System.out.println("执行finally块"); } } ``` 3. 在finally进行return: ``` public static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { System.out.println("除数不能为0"); } finally { System.out.println("执行finally块"); return -1; } } ``` 4. 在try进行throw异常: ``` public static int divide(int a, int b) throws ArithmeticException { try { return a / b; } catch (ArithmeticException e) { System.out.println("除数不能为0"); throw e; } finally { System.out.println("执行finally块"); } } ``` 5. 在catch进行throw异常: ``` public static int divide(int a, int b) throws ArithmeticException { try { return a / b; } catch (ArithmeticException e) { System.out.println("除数不能为0"); throw e; } finally { System.out.println("执行finally块"); } } ``` 6. 在finally进行throw异常: ``` public static int divide(int a, int b) throws ArithmeticException { try { return a / b; } catch (ArithmeticException e) { System.out.println("除数不能为0"); } finally { System.out.println("执行finally块"); throw new ArithmeticException("执行finally块时发生异常"); } } ``` 需要注意的是,如果在trycatchfinally都进行了return语句或throw异常语句,那么最终执行的是finally的语句。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值