当涉及从finally块返回的值时,在try块中有return语句是好的做法 [英] Is it good practice to have return statement in try block when returned value from finally block is concerned
问题描述
我想知道,返回
从尝试
阻止这是不错的做法?
I was wondering, is it good practice to return
from try
block?
package debug;
/**
*
* @author Owner
*/
public class Main {
public static void main(String[] args) {
System.out.println(fun());
}
static boolean cleanup() {
// Fail to cleanup.
return false;
}
static boolean fun() {
boolean everything_is_fine = true;
try {
System.out.println("open file stream");
return everything_is_fine;
} finally {
everything_is_fine = cleanup();
}
}
}
我首先想到的是打印 false
。但是,这是输出:
open file stream
true
如您所见,如果我在中有
阻止,我将错过 return
语句,请尝试最终
清理期间的失败状态。
As you can see, if I am having return
statement within try
block, I will miss the fail status during finally
cleanup.
我应该有代码为:
static boolean fun() {
boolean everything_is_fine = true;
try {
System.out.println("open file stream");
} finally {
everything_is_fine = cleanup();
}
return everything_is_fine;
}
只要涉及finally块的返回值,我避免从尝试返回?
推荐答案
您建议的代码(问题末尾)没问题。您可以从 finally
块返回,但您不应该 - 例如eclipse显示警告finally块无法正常完成。
Your suggested code (at the end of the question) is fine. You can return from the finally
block, but you should not - for example eclipse shows a warning "finally block does not complete normally".
事实上, try / finally
与返回$没有直接关系C $ C>。这似乎是这样,因为它是方法中唯一的构造,但是之后你可以有其他代码(例如 - 事件通知),然后返回。
In fact, the try/finally
aren't directly related to the return
. It seems so here, because it is the only construct in the method, but you can have other code after that (for example - event notifications), and then return.
至于你的问题 - 如果已经返回 finally
块,则无法更改返回变量的值。所以不要从返回
。
As for your question - you can't change the value of the returned variable in the finally
block if it is already returned. So don't return from try
.
这篇关于当涉及从finally块返回的值时,在try块中有return语句是好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!