(Java)try catch finally执行的顺序

public class Test {
	public static int testInt(){
		int x =1;
		try{
			x = 2;
			return x;
		}catch(Exception e){
			return x;
		}finally{
			x = 3;
		}
	}
	public static int testInt1(){
		int x =1;
		try{
			x = 2;
			return x;
		}catch(Exception e){
			return x;
		}finally{
			x = 3;
			return x;
		}
	}
	public static List<String> testList(){
		List<String> list = new ArrayList<>();
		try{
			list.add("try");
			return list;
		}catch(Exception e){
			list.add("exception");
			return list;
		}finally{
			list.add("finally");
		}
	}
	public static void main(String[] args){
		System.out.println(testInt());
		System.out.println(testInt1());
		System.out.println(testList());
	}
}

输出的结果为:

2
3
[try, finally]

解释说明:

当try或者catch中返回的类型是基本类型的时候

这种情况下,即使finally在对基本类型进行操作,返回的值也是try或者catch中的内容。
原因是:
在 try中返回的值,其实类似于当前范围内的局部变量,而不是这一个在函数内部的局部变量。

当try或者catch中返回的类型是引用类型的时候

因为引用对象返回的是对象在堆上的地址,所以finally中的代码对于堆上的对象的修改也是能被我们所捕捉到的。
所以在testList中返回的是try,finally。

当finally中存在返回的时候

会直接覆盖掉try(catch)中返回的内容,并且编译器会提示warn。这个时候返回的内容是finally中的值。

猜你喜欢

转载自blog.csdn.net/weixin_43872339/article/details/87877871