• 77 try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?


    try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?

    答:

    finally 一定会执行,即使是 catch 中 return 了,catch 中的 return 会等 finally 中的代码执行完之后,才会执行。

     

    try-catch-finally中return的执行情况:

    1. 在try中没有异常的情况下try、catch、finally的执行顺序 try --- finally

    2. 如果try中有异常,执行顺序是try --- catch --- finally

    3. 如果try中没有异常并且try中有return这时候正常执行顺序是try ---- finally --- return

    4. 如果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 (下文)
     

    1. 不管有没有异常,finally中的代码都会执行

    2. 当try、catch中有return时,finally中的代码依然会继续执行

    3. finally是在return后面的表达式运算之后执行的,此时并没有返回运算之后的值,而是把值保存起来,不管finally对该值做任何的改变,返回的值都不会改变,依然返回保存起来的值。也就是说方法的返回值是在finally运算之前就确定了的。

    4. 如果return的数据是引用数据类型,而在finally中对该引用数据类型的属性值的改变起作用,try中的return语句返回的就是在finally中改变后的该属性的值。

    5. 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;
    	}
    
    }
    

     

  • 相关阅读:
    向局域网共享文件夹 写文件(示例)
    安装adb之后出现 找不到设备的情况
    .net 下发送calendar
    解决api 跨域 webconfig添加节点
    String类为什么是不可变的
    Sql
    2020职业规划
    摘录
    Docker
    软件测试工程师的职责是什么
  • 原文地址:https://www.cnblogs.com/ynzj123/p/13053357.html
Copyright © 2020-2023  润新知