try catch finally中有return语句的执行情况及原因分析

前言

之前在学习Java异常时遇到了try cathc finally中有return的情况,但是到底return执不执行,以怎样的顺序执行,以及原因是什么,还没弄清楚。

1 执行顺序以及原因

先来看一个简单的例子,为了便于阅读方法的字节码指令,没有采用static方法

package chapter6;
/**
 * @author 小锅巴
 */
public class Finally {
    public int inc(){
        int x;
        try {
            x = 1;
            return x;
        } catch (Exception e) {
            x = 2;
            return x;
        }finally{
            x = 3;
        }
    }
    public static void main(String[] args){
        Finally f = new Finally();
        System.out.println(f.inc());
    }
}

使用javap反编译查看Finally.class中的字节码指令,重点关注下是否加载到了操作数栈(是否执行了iload_n指令,要注意栈是先进后出的)中以及栈顶局部变量的值,在阅读字节码指令之前,说明一下相关字节码指令的含义:

  1. iconst:将int常量(字面量)加载到操作数栈(进栈)
  2. istore:将字面量从操作数栈存储到局部变量表(Slot)中(出栈)
  3. iload:将一个int局部变量加载到操作数栈(进栈)
  4. ireturn:返回int局部变量表中的值(返回栈顶的值)
D:\Develop\Java\jdk1.8.0_65\bin>javap -c Finally
警告: 二进制文件Finally包含chapter6.Finally
Compiled from "Finally.java"
public class chapter6.Finally {
  public chapter6.Finally();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":
()V
       4: return

  public int inc();
    Code:
       0: iconst_1//加载1到操作数栈(进栈)
       1: istore_1//将1从操作数栈存储到局部变量表Slot(出栈)
       2: iload_1//将x(x=1)加载到操作数栈,结果就是x保存到了Slot中(进栈)
       3: istore        
       5: iconst_3//加载finally中的3(进栈)
       6: istore_1//将3存储到局部变量表,但是没有执行iload_1,并未将3加载到操作数栈,准确地说,处在栈顶的不是3(出栈)
       7: iload         4//将Slot中的值(3)放到栈顶,准备给ireturn调用
       9: ireturn//这条指令执行完,返回语句就执行完毕
      10: astore_2//给catch中定义的Exception e赋值,存储在Slot2中
      11: iconst_2//(进栈)
      12: istore_1//(出栈)
      13: iload_1 //(进栈),
      14: istore        4
      16: iconst_3//(进栈)
      17: istore_1//(出栈)
      18: iload         4//直接到这里吧,上面虽然加载了finally中的3(iconst_3)到操作数栈,但并未执行iload_1,还是没有加载到操作数栈,还是栈顶不是3,
    //加载了catch中的2(iconst_2)之后执行了iload_1(一次进栈),所以若发生异常并被catch捕获,将从catch中返回(覆盖了try的返回)
      20: ireturn
      21: astore_3
      22: iconst_3
      23: istore_1
      24: aload_3
      25: athrow
    Exception table:
       from    to  target type
           0     5    10   Class java/lang/Exception
           0     5    21   any
          10    16    21   any

  public static void main(java.lang.String[]);
    Code:
       0: new           #1                  // class chapter6/Finally
       3: dup
       4: invokespecial #27                 // Method "<init>":()V
       7: astore_1
       8: getstatic     #28                 // Field java/lang/System.out:Ljava/
io/PrintStream;
      11: aload_1
      12: invokevirtual #34                 // Method inc:()I
      15: invokevirtual #36                 // Method java/io/PrintStream.printl
n:(I)V
      18: return
}

D:\Develop\Java\jdk1.8.0_65\bin>

根据上述字节码指令的分析,不难得出输出的是1,若发生了异常并被catch捕获,那么输出的是2,如:

package chapter6;
/** 
 * 发生了异常并被catch捕获,将从catch中返回,输出2
 * @author 小锅巴
 */
public class Finally {
    public int inc(){
        int x;
        try {
            x = 1;
            x = x / 0;
            return x;
        } catch (Exception e) {
            x = 2;
            return x;
        }finally{
            x = 3;
        }
    }
    public static void main(String[] args){
        Finally f = new Finally();
        System.out.println(f.inc());
    }
}

那么如果finally中有return语句会怎么样呢,比如:

package chapter6;
/** 
 * finally中有return语句,将覆盖try和catch中的return语句
 * @author 小锅巴
 */
public class Finally {
    public int inc(){
        int x;
        try {
            x = 1;
            x = x/0;
            return x;
        } catch (Exception e) {
            x = 2;
            return x;
        }finally{
            x = 3;
            return x;
        }
    }
    public static void main(String[] args){
        Finally f = new Finally();
        System.out.println(f.inc());
    }
}

还是来查看并分析字节码指令:

D:\Develop\Java\jdk1.8.0_65\bin>javap -c Finally
警告: 二进制文件Finally包含chapter6.Finally
Compiled from "Finally.java"
public class chapter6.Finally {
  public chapter6.Finally();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":
()V
       4: return

  public int inc();
    Code:
       0: iconst_1
       1: istore_1
       2: goto          12//跳转到finally
       5: astore_2
       6: iconst_2
       7: istore_1
       8: goto          12//跳转到finally
      11: pop
      12: iconst_3//加载3到操作数栈(进栈)
      13: istore_1//(出栈)
      14: iload_1//(进栈)将3加载到了操作数数,所以finally中的返回语句将覆盖try和catch的语句
      15: ireturn
    Exception table:
       from    to  target type
           0     5     5   Class java/lang/Exception
           0    11    11   any

  public static void main(java.lang.String[]);
    Code:
       0: new           #1                  // class chapter6/Finally
       3: dup
       4: invokespecial #27                 // Method "<init>":()V
       7: astore_1
       8: getstatic     #28                 // Field java/lang/System.out:Ljava/
io/PrintStream;
      11: aload_1
      12: invokevirtual #34                 // Method inc:()I
      15: invokevirtual #36                 // Method java/io/PrintStream.printl
n:(I)V
      18: return
}

有个问题还需要注意,如果局部变量不是基本类型,而是引用类型,那么在finally中没有return语句但是通过引用修改了对象,则可能会改变返回的值。主要是因为java是值传递,没有引用传递,也就是说参数传递的是引用的拷贝,可以通过该拷贝修改对象的状态(修改实例变量),但是不能改变原引用所指向的对象(因为只是改变了拷贝的指向)从而指向别的对象。具体看后面的例子

2 实例

转自敏敏的博客,具体原因上面已经分析了。

网上有很多人探讨Java中异常捕获机制try…catch…finally块中的finally语句是不是一定会被执行?很多人都说不是,当然他们的回答是正确的,经过我试验,至少有两种情况下finally语句是不会被执行的

  1. try语句没有被执行到,如在try语句之前就返回了,这样finally语句就不会执行,这也说明了finally语句被执行的必要而非充分条件是:相应的try语句一定被执行到。
  2. 在try块中有System.exit(0);这样的语句,System.exit(0);是终止Java虚拟机JVM的,连JVM都停止了,所有都结束了,当然finally语句也不会被执行到。

当然还有很多人探讨Finally语句的执行与return的关系,颇为让人迷惑,不知道finally语句是在try的return之前执行还是之后执行?我也是一头雾水,我觉得他们的说法都不正确,我觉得应该是:finally语句是在try的return语句执行之后,return返回之前执行。这样的说法有点矛盾,也许是我表述不太清楚,下面我给出自己试验的一些结果和示例进行佐证,有什么问题欢迎大家提出来。

3.1 finally语句在return语句执行之后return返回之前执行的。

public class FinallyTest1 {

    public static void main(String[] args) {

        System.out.println(test1());
    }

    public static int test1() {
        int b = 20;

        try {
            System.out.println("try block");

            return b += 80; 
        }
        catch (Exception e) {

            System.out.println("catch block");
        }
        finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }
        }

        return b;
    }

}
输出:  
try block
finally block
b>25, b = 100
100

说明return语句已经执行了再去执行finally语句,不过并没有直接返回,而是等finally语句执行完了再返回结果。

如果觉得这个例子还不足以说明这个情况的话,下面再加个例子加强证明结论:

public class FinallyTest1 {

    public static void main(String[] args) {

        System.out.println(test11());
    }

    public static String test11() {
        try {
            System.out.println("try block");

           return test12();
      } finally {
           System.out.println("finally block");
       }
  }

  public static String test12() {
       System.out.println("return statement");

       return "after return";
   }

}
输出:
try block
return statement
finally block
after return

3.2 finally块中的return语句会覆盖try块中的return返回。

public class FinallyTest2 {

    public static void main(String[] args) {

        System.out.println(test2());
    }

    public static int test2() {
        int b = 20;

        try {
            System.out.println("try block");

            return b += 80;
        } catch (Exception e) {

            System.out.println("catch block");
        } finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }

            return 200;
        }

        // return b;
    }

}
输出:  
try block
finally block
b>25, b = 100
200

这说明finally里的return直接返回了,就不管try中是否还有返回语句,这里还有个小细节需要注意,finally里加上return过后,finally外面的return b就变成不可到达语句了,也就是永远不能被执行到,所以需要注释掉否则编译器报错。

3.3如果finally语句中没有return语句覆盖返回值,那么原来的返回值可能因为finally里的修改而改变也可能不变。

不改变的例子:

public class FinallyTest3 {

    public static void main(String[] args) {

        System.out.println(test3());
    }

    public static int test3() {
        int b = 20;

        try {
            System.out.println("try block");

            return b += 80;
        } catch (Exception e) {

            System.out.println("catch block");
        } finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }

            b = 150;
        }

        return 2000;
    }

}
输出:  
try block
finally block
b>25, b = 100
100

改变的例子

import java.util.*;

public class FinallyTest6
{
    public static void main(String[] args) {
        System.out.println(getMap().get("KEY").toString());
    }

    public static Map<String, String> getMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("KEY", "INIT");

        try {
            map.put("KEY", "TRY");
            return map;
        }
        catch (Exception e) {
            map.put("KEY", "CATCH");
        }
        finally {
            map.put("KEY", "FINALLY");
            map = null;
        }

        return map;
    }
}
输出:
FINALLY

为什么测试用例1中finally里的b = 150;并没有起到作用而测试用例2中finally的map.put(“KEY”, “FINALLY”);起了作用而map = null;却没起作用呢?这就是Java到底是传值还是传址的问题了,具体请看精选30道Java笔试题解答,里面有详细的解答,简单来说就是:Java中只有传值没有传址,这也是为什么map = null这句不起作用。这同时也说明了返回语句是try中的return语句而不是 finally外面的return b;这句,不相信的话可以试下,将return b;改为return 294,对原来的结果没有一点影响。

3.4 try块里的return语句在异常的情况下不会被执行,这样具体返回哪个看情况。

public class FinallyTest4 {

    public static void main(String[] args) {

        System.out.println(test4());
    }

    public static int test4() {
        int b = 20;

        try {
            System.out.println("try block");

            b = b / 0;

            return b += 80;
        } catch (Exception e) {

            b += 15;
            System.out.println("catch block");
        } finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }

            b += 50;
        }

        return 204;
    }

}
输出:  
try block
catch block
finally block
b>25, b = 35
85

这里因 为在return之前发生了除0异常,所以try中的return不会被执行到,而是接着执行捕获异常的catch 语句和最终的finally语句,此时两者对b的修改都影响了最终的返回值,这时return b;就起到作用了。当然如果你这里将return b改为return 300什么的,最后返回的就是300,这毋庸置疑。

3.5 当发生异常后,catch中的return执行情况与未发生异常时try中return的执行情况完全一样。

public class FinallyTest5 {

    public static void main(String[] args) {

        System.out.println(test5());
    }

    public static int test5() {
        int b = 20;

        try {
            System.out.println("try block");

            b = b /0;

            return b += 80;
        } catch (Exception e) {

            System.out.println("catch block");
            return b += 15;
        } finally {

            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }

            b += 50;
        }

        //return b;
    }

}
输出:  
try block
catch block
finally block
b>25, b = 35
35

说明了发生异常后,catch中的return语句先执行,确定了返回值后再去执行finally块,执行完了catch再返回,finally里对b的改变对返回值无影响,原因同前面一样,也就是说情况与try中的return语句执行完全一样。

总结

最后来总结一下:try块catch块和finally块都可有return语句,当发生异常且被catch捕获时,catch中若有return语句且对try中的局部变量进行了修改,那么catch中的return将覆盖try中的return并修改局部变量;若finally中没有return语句,且对try或catch中的局部变量进行了修改,若局部变量是基本类型,局部变量的返回值不会被修改,若是引用类型,则会被修改;若finally中有return语句,finally中的return语句将覆盖try或catch中的return语句,局部变量的返回值将被修改。

参考资料:
1. 深入理解Java虚拟机
2. http://www.cnblogs.com/lanxuezaipiao/p/3440471.html
3. http://blog.csdn.net/ns_code/article/details/17485221
4. https://www.ibm.com/developerworks/cn/java/j-lo-finally/

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值