如果“try”或“catch”块中有“return”,是否会执行“finally”块?
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,
try/catch
表达式的结果将是try
或catch
块的最后一行,但finally
块无论如何都会执行Yes,
The result of the
try/catch
expression will be the last line of either thetry
orcatch
block, but thefinally
block will always execute no matter what是的。
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 thetry
block. It happens on ordinary return, when an exception is thrown and caught, and when an exception is thrown that isn't caught by thistry
block. The only thing that will prevent it running is if the program is unable to leave thetry
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 thetry
block that thefinally
block will be executed before the process actually dies.来自 文档:
From the docs: