简单谈谈try{}catch(){}finally{} 中提前return的影响

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013234928/article/details/89415675

也许大家可能没有注意到,在try{}catch(){}finally{} 中提前return时是会有影响最终结果的。曾有面试提中就有这样的问题。

try …finally 中的return 语句影响

  1. finally块的代码一定会执行
  2. finally块的代码不会改变try块catch块的返回值
  3. 如果try块catch块return的是引用类型的地址,finally块可以改变返回对象的状态

先上代码,直接分析

//值传递
public static int print() {
		int i=0;
		try {
			i=10;
			int m=1/0;//	1
			return i;//		2
		}catch (Exception e) {
			i=20;
			//return i;//	3
		}finally {
			i=30;
			//return i;//	4
		}
		return i;//		5
	}

//分析:
1、当标记1、5开启,3、4注释,2随意;此时输出 i = 30,若没有finally ,则输出i = 20
2、当标记1、3、5处开启,2、4注释,此时输出 i = 20 ,
2、当标记2、5 开启,1、3、4 处 被注释时,i = 10

总结:当try块或者catch块中提前返回时,finally块的语句不会改变return的返回值


在引用传递是会有影响吗?

//引用传递
public static int[] print(){
		 int[] x = new int[2];
        try{
            x[0] = 1;
            throw new Exception();
        } catch (Exception e){
            x[1] = 2;
            return x;
        }finally {
            x[1] = 3;
        }
    }

大家可能没想到吧,最终结果成了 x :[1, 3],索引1处值发生改变了

由此可以得出:finally块可以改变返回对象属性的状态

猜你喜欢

转载自blog.csdn.net/u013234928/article/details/89415675