为什么finally中的代码即使在try块中返回了也会执行?
代码: <代码>
public String get() {
try {
//doSomething
return "Hello";
}
finally {
System.out.print("Finally");
}
<代码> 这段代码是如何执行的呢?
Code:
public String get() {
try {
//doSomething
return "Hello";
}
finally {
System.out.print("Finally");
}
How does this code execute?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为这就是
finally
块的全部要点 - 无论您离开try
块,它都会执行,除非虚拟机本身突然关闭。通常,
finally
块用于清理资源 - 您不会希望仅仅因为在try
块期间返回而使文件句柄保持打开状态,不是吗?现在,您可以将该清理代码放在 return 语句之前 - 但如果代码抛出异常,则不会清理它。使用finally
,清理代码将执行但是您离开该块,这通常是您想要的。请参阅 JLS 第 14.20.2 节更多细节 - 并注意所有路径如何涉及
finally
块的执行。Because that's the whole point of a
finally
block - it executes however you leave thetry
block, unless the VM itself is shut down abruptly.Typically
finally
blocks are used to clean up resources - you wouldn't want to leave a file handle open just because you returned during thetry
block, would you? Now you could put that clean-up code just before the return statement - but then it wouldn't be cleaned up if the code threw an exception instead. Withfinally
, the clean-up code executes however you leave the block, which is generally what you want.See JLS section 14.20.2 for more details - and note how all paths involve the
finally
block executing.最后,无论 try 块中发生什么(失败、返回、异常、完成等),ALWAYS 都会被执行。
如果您不希望执行此代码,可以随时将其放在 try/catch/finally 语句之后。
Finally ALWAYS gets executed, no matter what happens in the try block (fail, return, exception, finish etc.).
If you don't want this code to be executed, you could always placed it after the try/catch/finally statement.
这正是
finally
的用途:当try
块离开时,内部的代码将执行,无论如何(除了通过 JVM 关闭)System.exit()
或外部原因)。That's exactly what
finally
is for: the code inside will execute when thetry
block is left, no matter how (except the JVM shutting down viaSystem.exit()
or external reasons).