Java try-finally 返回设计问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4185340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java try-finally return design question
提问by Travis Webb
In Java, a try { ... } finally { ... } is executed somewhat unintuitively to me. As illustrated in another question, Does finally always execute in Java?, if you have a return statement in the try block, it will be ignored if a finally block is defined. For example, the function
在 Java 中, try { ... } finally { ... } 的执行对我来说有点不直观。如另一个问题所示,最终是否总是在 Java 中执行?, 如果在 try 块中有 return 语句,如果定义了 finally 块,它将被忽略。例如,函数
boolean test () {
try {
return true;
}
finally {
return false;
}
}
will always return false. My question: why is this? Is there a particular philosophy behind this design decision made by Java? I appreciate any insight, thank you.
将始终返回 false。我的问题:这是为什么?Java 做出的这个设计决定背后有什么特别的哲学吗?我很欣赏任何见解,谢谢。
Edit: I'm particularly interested as to 'why' Java thinks it's ok to violate the semantics that I define. If I 'return' in a try block, the method should return right then and there. But the JVM decides to ignore my instruction and return from a subroutine that actually hasn't yetbeen reached.
编辑:我对“为什么”Java 认为可以违反我定义的语义特别感兴趣。如果我在 try 块中“返回”,则该方法应该立即返回。但是 JVM 决定忽略我的指令并从实际上尚未到达的子例程返回。
采纳答案by Andrzej Doyle
Technically speaking, the return
in the try block won't be ignored if a finally
block is defined, only if that finally block also includes a return
.
从技术上讲,return
如果定义了一个finally
块,则不会忽略 try 块中的,只有当该 finally 块还包含.return
It's a dubious design decision that was probablya mistake in retrospect (much like references being nullable/mutable by default, and, according to some, checked exceptions). In many ways this behaviour is exactly consistent with the colloquial understanding of what finally
means - "no matter what happens beforehand in the try
block, always run this code." Hence if you return true
from a finally
block, the overall effect must always to be to return true, no?
这是一个可疑的设计决定,回想起来可能是一个错误(很像默认情况下引用可以为空/可变,并且根据某些检查异常)。在许多方面,这种行为与对finally
含义的通俗理解完全一致——“无论try
块中事先发生了什么,始终运行此代码。” 因此,如果您return true
来自一个finally
块,则整体效果必须始终返回 true,不是吗?
In general, this is seldom a good idiom, and you should use finally
blocks liberally for cleaning up/closing resources but rarely if ever return a value from them.
一般来说,这很少是一个好的习惯用法,您应该大量使用finally
块来清理/关闭资源,但很少从它们返回值。
回答by Peter ?tibrany
If code in finally block ends abruptly, it changes return value/exception from try
block. This is considered to be bad practice, and you should not do that.
如果 finally 块中的代码突然结束,它会更改try
块的返回值/异常。这被认为是不好的做法,你不应该这样做。
Among other places, this is also discussed in Java Puzzlersbook.
在其他地方,这也在Java Puzzlers书中讨论过。
回答by anirvan
the finally
construct is a facility provided by the JLS to handle a code prone to some exception. the developer can utilise this facility to ensure a graceful recovery from an exception. to use the finally
construct in the manner you've described doesn't make for a good practice. for that matter, it is never good to return
anything from the finally block.
so as you asekd, the "philosophy" is to handle any abrupt completion of code. if returning a certain value as part of handling such a state is required, that should be done within the catch
block.
该finally
构造是 JLS 提供的一种工具,用于处理易于出现某些异常的代码。开发人员可以利用此功能来确保从异常中正常恢复。finally
以您所描述的方式使用该构造并不是一种好的做法。就此而言,return
finally 块中的任何内容都没有好处。
所以正如你所问的,“哲学”是处理代码的任何突然完成。如果需要返回某个值作为处理此类状态的一部分,则应在catch
块内完成。
回答by Mike Godin
If you call javac with -Xlint, then an appropriate warning will be generated indicating that you should not call return from a finally clause. For example (compiling a simple class with the above test()
method):
如果您使用 -Xlint 调用 javac,则会生成适当的警告,指示您不应从 finally 子句中调用 return。例如(用上述test()
方法编译一个简单的类):
javac -Xlint foo.java
foo.java:13: warning: [finally] finally clause cannot complete normally
}
^
1 warning
回答by Starrow Pan
Though The finally block is made for closing resources, and a return statement is generally not supposed to be there, and Eclipse warns that "finally block does not complete normally", I found in some circumstances a "finally return" is still desirable.
虽然finally块是为关闭资源而制作的,并且通常不应该有return语句,并且Eclipse警告“finally块没有正常完成”,但我发现在某些情况下“finally return”仍然是可取的。
ResponseType response = new ResponseType();
try{
//set some properties of the response object.
response.setStatus(1);
//return response;
}catch (Exception e){
//Some other properties of the response object according to the exception.
response.setStatus(0);
//return response;
}finally{
return response;
}
If I don't put the return clause in the finally block, I would have to repeat it in try and catch blocks and the current code is a little clearer.
如果我不将 return 子句放在 finally 块中,我将不得不在 try 和 catch 块中重复它,当前代码会更清晰一些。
回答by Nutan
check this for reference Does finally always execute in Java?
检查这个以供参考 最终总是在Java中执行吗?
"A try statement with a finally block is executed by first executing the try block. Then there is a choice:
If execution of the try block completes normally, [...]
If execution of the try block completes abruptly because of a throw of a value V, [...]
If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded)."
“通过首先执行 try 块来执行带有 finally 块的 try 语句。然后有一个选择:
如果 try 块的执行正常完成,[...]
如果 try 块的执行由于抛出一个值 V, [...]
如果 try 块的执行由于任何其他原因 R 突然完成,则执行 finally 块。然后有一个选择:
如果 finally 块正常完成,则 try 语句突然完成 for原因 R。
如果 finally 块因原因 S 突然完成,则 try 语句因原因 S 突然完成(并且原因 R 被丢弃)。
回答by TheSprinter
Purpose of finally
:
目的finally
:
Java people has created
finally
block for closing operation,which has to be performed in both cases (e.g exception occurred or no exception).It is not recommended to use return statement in
finally
block as it overrides both thereturn
statement fromcatch
&try
block. and warns "finally block does not complete normally"finally
block should have return statement only when bothtry
andcatch
has noreturn
statement.Incase both
try
andcatch
have different value then we should not keep anything infinally
block,- and if we are returning same value in both
try
andcatch
block then its better to keep return infinally
and remove return in bothtry
&catch
block. - If
finally
throws any exception then thereturn
inside that block will not execute.
Java 人为
finally
关闭操作创建了块,这在两种情况下都必须执行(例如发生异常或没有异常)。不建议在
finally
块中使用 return 语句,因为它会覆盖&块中的return
语句。并警告“ finally 块没有正常完成”catch
try
finally
块应该有return语句,只有当两者try
并catch
没有return
声明。柜面都
try
和catch
有不同的值,那么我们不应该将你的东西在finally
块,- 如果我们在两个
try
和catch
块中都返回相同的值,那么最好finally
在两个try
&catch
块中保留 return并删除 return 。 - 如果
finally
抛出任何异常,则该return
块内部将不会执行。
finally
block will not execute only when:
finally
块不会仅在以下情况下执行:
- On invoke of System.exit()
- kill process
- application/environment crashes
- stackoverflow/infinite loop
- 调用 System.exit()
- 杀死进程
- 应用程序/环境崩溃
- 堆栈溢出/无限循环