更新时间:2023-11-09 17:43:58
因为如果它没有' t,资源不会被清理干净。
这是一个直截了当的答案,它几乎就是你所需要的。问题是,无论何时退出try ... finally
阻止,无论如何,中的代码
块 总是 执行。这意味着如果你离开是因为你:
1)到达尝试
代码的末尾 - 执行最后阻止。
2)执行return
语句 - 执行finally块。
3)抛出异常使用throw
- 执行finally块。
4)在被调用的方法中导致异常,即使它是100个方法深,也会出错并且它不会被catch
处理 - 执行finally块。
5)使用catch
处理异常:当你以任何方式退出catch
块时 - 执行finally块。
整个想法是你的代码永远不会继续超过try ... finally
而不执行中的代码
阻止并释放你分配的资源。
请看下面这个帖子。
为什么即使它在try块中返回,最终的代码也会执行? [ ^ ]
最后块在任何情况下都会执行。最后块在实时场景中扮演着非常重要的角色。
例如假设在执行某个代码块期间你有一个开放的数据库连接。执行时出错提升,这会中断你正常的执行流程。现在控制将进入Try块,这反过来会抛出相应的错误来捕获block.Note在这里处理错误,但你的数据库连接仍然是打开的。因为数据库是开放的用户,当时没有其他用户可以做交易。所以你应该做d尽可能晚地打开你的连接并尽快关闭连接。为了确保在任何情况下关闭连接,在finally块中提供你的数据库关闭连接命令以确保关闭打开连接。所以最后阻塞是非常重要的。
WHY finally
will execute even when there is a return in try block?
I know its by design, in finally
block i should do resource cleanup - that's why the finally block is always executed no matter what the exception handling code is.
But "WHY" it will execute is my question? This was asked to my friend in an interview, so even i got confused after discussing with him, please clarify, thanks in advance.?
Because if it didn't, resources would not get cleaned up.
That's the blunt answer and it's pretty much all you need. The thing is, whenever you exit atry...finally
block, by whatever means, the code in thefinally
block is always executed. That means if you leave because you:
1) Got to the end of thetry
code - execute the finally block.
2) Execute areturn
statement - execute the finally block.
3) Throw an exception usingthrow
- execute the finally block.
4) Cause an exception in a called method, even if it is 100 methods deep, by making a mistake and it isn't handled by acatch
anywhere - execute the finally block.
5) Usecatch
to handle an exception: when you exit thecatch
block by any means - execute the finally block.
The whole idea is that you code will never continue past thetry...finally
without executing the code in thefinally
block and releasing the resources you allocated.
Hi, please see this thread below.
Why code in finally will execute even it has returned in try block?[^]
Finally block will execute anyway at any circumstance.Finally block is having very important role in real time scenario.
Suppose for example you have an open database connection during execution of certain code block.During execution an error raised,which interrupted your normal flow of execution.Now control will go inside Try block which in turn will throw respective error to catch block.Note here that error is handled,but your connection to database is still open.As database is open for certain user,no other user will be able to do transaction at that time.So you should open your connection as late as possible and should close connection as early as possible.To ensure closing of connection at any circumstance provide your database close connection command inside finally block to ensure closing of open connection.So finally block is very important.