为什么finally中的代码即使在try块中返回了也会执行?

发布于 2024-10-16 16:30:02 字数 227 浏览 1 评论 0原文

代码: <代码>

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里°也失望 2024-10-23 16:30:02

因为这就是 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 the try 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 the try 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. With finally, 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.

作妖 2024-10-23 16:30:02

最后,无论 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.

橘虞初梦 2024-10-23 16:30:02

这正是 finally 的用途:当 try 块离开时,内部的代码执行,无论如何(除了通过 JVM 关闭) System.exit() 或外部原因)。

That's exactly what finally is for: the code inside will execute when the try block is left, no matter how (except the JVM shutting down via System.exit() or external reasons).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文