如果“try”或“catch”块中有“return”,是否会执行“finally”块?

发布于 2024-12-10 19:26:45 字数 170 浏览 0 评论 0原文

使用 try-catch-finally 结构来检索数据库记录,似乎我需要在 try 块内返回一个值,以防万一一切正常(就像在异常的情况下)函数并不意味着能够达到)。但是如果我返回到 try 内部,是否会到达 finally 代码(以关闭连接等)?

Using a try-catch-finally construction to retrieve a database record, it seems that I need to return a value inside a try block in case everything was fine (as in case of an exception the end of the function is not meant to be reached). But If I return inside try, is finally code going to be reached (to close the connection etc.)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

海拔太高太耀眼 2024-12-17 19:26:45

是的,

try/catch 表达式的结果将是 trycatch 块的最后一行,但 finally 块无论如何都会执行

Yes,

The result of the try/catch expression will be the last line of either the try or catch block, but the finally block will always execute no matter what

時窥 2024-12-17 19:26:45

是的。

finally 的要点是确保执行一些清理代码,无论代码使用什么路径离开 try 块。它发生在普通返回、抛出并捕获异常时,以及抛出此 try 块未捕获的异常时。唯一阻止它运行的是程序根本无法离开 try 块;其中的无限循环,或者进程被某种阻止正常处理发生的方式杀死,或者类似的事情。我非常确定,即使您从 try 块内部退出进程,finally 块也会在进程实际终止之前执行。

Yes.

The point of a finally is to ensure that some cleanup code is executed no matter what path the code uses to leave the try block. It happens on ordinary return, when an exception is thrown and caught, and when an exception is thrown that isn't caught by this try block. The only thing that will prevent it running is if the program is unable to leave the try block at all; an infinite loop inside it, or the process being killed by some means that prevents this normal processing from happening, or something of that order. I'm pretty sure even if you exit the process from inside the try block that the finally block will be executed before the process actually dies.

水染的天色ゝ 2024-12-17 19:26:45

来自 文档

如果在 try 或 the try 中遇到 return 语句
catch 块中,finally 块仍然会被执行。

From the docs:

If a return statement is encountered inside either the try or the
catch blocks, the finally block will still be executed.

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