摘要
本段代码块主要验证try,catch,finally的执行跳转返回逻辑
try返回值,finally只赋值,不返回值
/**
* <p>
* 如果finally不返回result,只是赋值(i="set in finally"),
* 只会修改到栈帧中的局部变量result,
* 不会修改到虚拟机栈返回值,此时虚拟机返回值位置存储的还是result="set in try"。
* </p>
* 执行返回结果:“set in try”
* @return
*/
private String testReturnInTry() {
String result = "init";
try{
result = "set in try";
return result;
}catch (Exception e){
result = "set in catch";
return result;
}finally {
result = "set in finally";
}
}
catch返回值,finally只赋值,不返回值
/**
* <p>
* 如果finally不返回result,只是赋值(i="set in finally"),只会修改到栈帧中的局部变量result,
* 不会修改到虚拟机栈返回值,此时虚拟机返回值位置存储的是result="set in catch"。
* </p>
* 执行返回结果:"set in catch"
* @return
*/
private String testReturnInCatch() {
String result = "init";
try{
result = "set in try";
throw new RuntimeException();
}catch (Exception e){
result = "set in catch";
return result;
}finally {
result = "set in finally";
}
}
finally返回值
/**
* <p>
* 如果finally返回result,不仅会修改到栈帧中的局部变量result,
* 还会把最新的result值更新到虚拟机栈返回值存储位置。
* </p>
* 执行返回结果:"set in finally"
* @return
*/
private String testReturnInFinally() {
String result = "init";
try{
result = "set in try";
//A:执行效果同B
return result;
//B:执行效果同A
// throw new RuntimeException();
}catch (Exception e){
result = "set in catch";
return result;
}finally {
result = "set in finally";
return result;
}
}