答:
?
在try中没有异常的情况下try、catch、finally的执行顺序 try --- finally
如果try中有异常,执行顺序是try --- catch --- finally
如果try中没有异常并且try中有return这时候正常执行顺序是try ---- finally --- return
如果try中有异常并且try中有return这时候正常执行顺序是try----catch---finally--- return
总之 finally 永远执行!
?
原文链接: http://blog.sina.com.cn/s/blog_74be444c0100vlqa.html  (上文)
原文链接: http://www.mamicode.com/info-detail-2875638.html  (下文)
?
不管有没有异常,finally中的代码都会执行
当try、catch中有return时,finally中的代码依然会继续执行
finally是在return后面的表达式运算之后执行的,此时并没有返回运算之后的值,而是把值保存起来,不管finally对该值做任何的改变,返回的值都不会改变,依然返回保存起来的值。也就是说方法的返回值是在finally运算之前就确定了的。
如果return的数据是引用数据类型,而在finally中对该引用数据类型的属性值的改变起作用,try中的return语句返回的就是在finally中改变后的该属性的值。
finally代码中最好不要包含return,程序会提前退出,也就是说返回的值不是try或catch中的值
?
参考代码:
// 当try、catch中有return时,finally中的代码会执行么?
public class TryCatchTest {
	public static void main(String[] args) {
//		System.out.println("return的返回值:" + test());
//		System.out.println("包含异常return的返回值:" + testWithException());
		System.out.println("return的返回值:" + testWithObject().age); // 测试返回值类型是对象时
	}
	// finally是在return后面的表达式运算之后执行的,此时并没有返回运算之后的值
	//,而是把值保存起来,不管finally对该值做任何的改变,返回的值都不会改变,依然返回保存起来的值。
	//也就是说方法的返回值是在finally运算之前就确定了的。
	static int test() {
		int x = 1;
		try {
			return x++;
		} catch(Exception e){
			
		}finally {
			System.out.println("finally:" + x);
			++x;
			System.out.println("++x:" + x);
			// finally代码中最好不要包含return,程序会提前退出,
			// 也就是说返回的值不是try或catch中的值
			// return x;
		}
		return x;
	}
	
	static int testWithException(){
		Integer x = null;
		try {
			x.intValue(); // 造个空指针异常
			return x++;
		} catch(Exception e){
			System.out.println("catch:" + x);
			x = 1;
			return x; // 返回1
//			return ++x; // 返回2
		}finally {
			x = 1;
			System.out.println("finally:" + x);
			++x;
			System.out.println("++x:" + x);
			// finally代码中最好不要包含return,程序会提前退出,
			// 也就是说返回的值不是try或catch中的值
//			 return x;
		}
	}
	
	static Num testWithObject() {
		Num num = new Num();
		try {
			return num;
		} catch(Exception e){
			
		}finally {
			num.age++; // 改变了引用对象的值
			System.out.println("finally:" + num.age);
		}
		return num;
	}
	
	static class Num{
		public int age;
	}
}
?
77 try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?
原文:https://www.cnblogs.com/ynzj123/p/13053357.html