如何在finally块中访问返回值
Published:
11 Jun 2015
Category:
尽管JVM是基于栈的虚拟机,但Java语言却不允许你去访问这个栈。但其实在某些场景下(尽管是不太常见),这个功能是非常实用的。
示例
方法返回的结果会存储在栈上。看下这段代码:
public int method() {
if (something)
return 1;
...
if (somethingElse)
return 2;
...
return 0;
}
如果我们不考虑[停机问题](http://it.deepinmind.com/%5BHalting%20problem%5D(http://en.wikipedia.org/wiki/Halting_problem),错误处理,以及其它学术上的问题,可以这么说,上述方法“肯定”会返回0,1或者2。并且这个值会存储在栈上,然后才会跳出这个方法。
有时候还会有这么一种情况,就是希望在返回某个特定值的时候执行特定的操作。大家可能又会为 该不该使用多重return语句陷入无止境的口水仗了,这个方法就会变成这样:
public int method() {
int result = 0;
if (something)
result = 1;
...
if (somethingElse)
result = 2;
...
// Important action here prior