try{}catch{}finally{}中加入return后的执行顺序

在网上看到一些关于在try{}catch{}finally{}中加入return后的执行顺序的讨论,不衷一是,于是自己写了个例子测试,过程和结论如下。  

  在try{}catch{}finally{}程序中,无论是否发生异常且无论try或catch语句块中包含什么代码("System.exit();"除外),finally语句块中的代码都会被执行。但当try语句块中包含return语句时执行顺序有点不一样。

  场景一:   


public class TestFinally {

    
public static void main(String[] args) 
{
        System.out.print(returnValue());
    }

    
    
public static int returnValue(){
        
int i = 0;                // L1

        try{                
            i 
= 1;                // L2

            return i = i + 5;    // L3
        }
 finally {            
            i 
= 2;                // L4

        }

    }

}

          returnValue()方法中的语句执行顺序为"L1, L2, L3, L4, L3",最后执行的是try语句块中的return语句,但returnValue()的返回值是6,看起来似乎finally语句块中对变量i的赋值未起作用,但实际上Debug的话会发现执行完finally语句块后转到return语句时变量i的值是新值2,但为什么return的是6呢?个人分析认为这是因为每一次执行L3时实际上不执行return,而是执行了"i = i + 5;"(这时i==6)并将i值存入某个临时变量 "xTemp = i; "(xTemp == 6),而后执行了finally中的 "i = 2;",最后执行try语句块中的return语句实际上"return xTemp;"。

  场景二:


public class TestFinally {

    
public static void main(String[] args) 
{
        System.out.print(returnValue());
    }

    
    
public static int returnValue(){
        
int i = 0;                // L1

        try{                
            i 
= 1;                // L2

            return i = i + 5;    // L3
        }
 finally {            
            i++;                  // L4

            return i;            // L5
        }

    }

}

  此时returnValue()方法中的语句执行顺序为"L1, L2, L3, L4, L5",最后执行的是finally语句块中的return语句,返回值是7。即try语句块中的return语句中的"i = i + 5;"得到了执行,最后由finally语句块中的return语句返回,try语句块中的return的返回功能不起作用了。

原文地址:https://www.cnblogs.com/davidshi/p/3491734.html