try catch finally 执行路径问题

面试中常出的题目,关于try catch 与finally的代码执行路径问题。

之前只记住了finally中的一定执行,执行顺序没有仔细琢磨。

1、比如是在return之前再执行finally,还是在try或者catch之后执行?

之前有点糊涂,其实try catch finally是一个整体的语法,与后面的代码块没啥关系,finally的含义是紧跟着try或者catch执行。

2、在try或者catch中已经return了还会不会执行?

之前记住的一定会执行是没有问题的,无论出现各种为,finally中的代码一定会执行,下面的代码noException函数示例,try中已经return了但finally中的代码还是会执行。

这里写上自己加深一下印象吧


package exception;

public class TestRunWay {

	public static void main(String [] args)
	{
		catchException();
		noException();
		
		
	}
	
	//执行会出现异常的方法
	public static void catchException()
	{
		try{
			int i = 1/0;
			System.out.println(" catchException do something wrong!");
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			System.out.println("catchException In finally!");
			
		}
		
		System.out.println("catchException after finally!");
	}
	
	//执行不会出现异常的方法
	public static void noException()
	{
		try{
			int i = 0;
			System.out.println("noException do nothing");
			return;//注意这里有返回哦
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			System.out.println("noException In finally!");
		}
		
		System.out.println("noException position after finally!");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值