今天遇到了一个问题

public int inc() {

   int x;

   try {

       x = 1;

       return x;

   } catch (Exception e) {

       x = 2;

       return x;

   } finally {

       x = 3;

   }

}

判断返回值。后来看Java虚拟机的时候才知道底层的知识。先看编译好的class文件

public int inc();

    0  iconst_1

    1  istore_1 [x]

    2  iload_1 [x]

    3  istore 4

    5  iconst_3

    6  istore_1 [x]

    7  iload 4

    9  ireturn

   10  astore_2 [e]

   11  iconst_2

   12  istore_1 [x]

   13  iload_1 [x]

   14  istore 4

   16  iconst_3

   17  istore_1 [x]

   18  iload 4

   20  ireturn

   21  astore_3

   22  iconst_3

   23  istore_1 [x]

   24  aload_3

   25  athrow

   省略其他的不必要信息,0-3行完成了对对变量X的赋值,同时将X值赋值到第四个本地变量表中。

   5-9行将X赋值为3, iload 4 将本地变量 读入到方法栈顶, ireturn 返回栈顶变量值。

   如果出现异常则跳转到10行继续。此时将X赋值为2,同时复制到本地变量表4,返回时iload 4 将本        地变量 读入到方法栈顶, ireturn 返回栈顶变量值。

    如果出现异常且不为Exception则跳转到21行执行。


   查看Exception  table

        Exception Table:

       [pc: 0, pc: 5] -> 10 when : java.lang.Exception

       [pc: 0, pc: 5] -> 21 when : any

       [pc: 10, pc: 16] -> 21 when : any

   
   可以看到跳转的行数和条件。

   此时可以得到结论:

   没有异常返回1,有Exception异常返回2,非Exception无返回值正常退出。

   感谢深入《深入理解JVM虚拟机》这本书的启示。