程序输出
hello
程序运行分析
- 通过字节码可以看到,程序在执行return之前,执行了finally块中的代码;
- finally块中的代码对src进行了赋值 ,但注意:从本地变量的角度看,finally块中的src和try中的src并不是一个;
- 在执行finally中代码前,try中的src在本地变量表中的位置从0移到了2,finally中src的赋值在对本地变量表0号位置的变量进行操作;
- 在执行完finally中的代码后,程序将本地变量表中2号位置的"hello"返回,故程序最终的返回为"hello";
- 虽然程序没有写catch代码,但生成的字节码中是有catch的逻辑的:先将捕获的异常存入本地变量表1号位置,再执行finally中的代码,将"imooc"存入本地变量表的0号位置,最后将异常抛出;
public class TryFinally {
/**
public static java.lang.String f1();
descriptor: ()Ljava/lang/String;
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=3, args_size=0
0: ldc #34 // String hello
2: astore_0
3: aload_0
4: astore_2
5: ldc #36 // String imooc
7: astore_0
8: aload_2
9: areturn
10: astore_1
11: ldc #36 // String imooc
13: astore_0
14: aload_1
15: athrow
* */
public static String f1() {
String str = "hello";
try{
return str;
}
finally{
str = "imooc";
}
}
public static void main(String[] args) {
System.out.println(f1());
}
}