参考答案:
对于 try 和 finally 至少一个语句块包含 return 语句的情况:
- finally 语句块会执行
- finally 没有 return,finally 对 return 变量的重新赋值修改无效
- try 和 finally 都包含 return,return 值会以 finally 语句块 return 值为准
如下面的例子
public static void main(String[] args) {
System.out.println(getString());
}
public static String getString() {
String str = "A";
try {
str = "B";
return str;
} finally {
System.out.println("finally change return string to C");
str = "C";
}
}
结果:
finally change return string to C
B
finally 语句块中新增 return 语句
public static void main(String[] args) {
System.out.println(getString());
}
public static String getString() {
String str = "A";
try {
str = "B";
return str;
} finally {
System.out.println("finally change return string to C");
str = "C";
return str;
}
}
结果:
finally change return string to C
C
finally 语句块中新增 return 语句字节码可以看出34是areturn
finally语句中可以看出,最后是athrow ,areturn在20就确定好返回结果了。