最终阻止真正需要清理代码(如关闭流)? [英] Is finally block really necessary for the clean up code (like closing streams)?

查看:115
本文介绍了最终阻止真正需要清理代码(如关闭流)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑,为什么我需要把清理代码放在一个终止块中。

I am very confused as to why do I need to need to put the clean-up code like closing streams in a finally block.

我已经看到,无论什么(无论是否有例外),最终块中的代码将会运行;并且在 finally 块运行之后,该方法的其余部分将继续。

I've read that the code in finally block will run no matter what (whether there's an exception); and after the finally block runs, the rest of the method continues.

我的问题是:如果剩下的方法必须继续,那么为什么在函数中的try / catch块之后我不会把清理代码?

My question is: if the rest of the method has to continue then why don't I put the clean-up code after my try/catch block in a function?

推荐答案

如果抛出未捕获的异常,finally块将始终运行,但该方法中的其余代码将被跳过

The finally block will always run if an uncaught exception is thrown, but the rest of the code in the method will be skipped.

所以如果在finally块之后放置清理代码,如果有异常,它将不会被调用。

So if you put clean-up code after the finally block, it won't get called if there is an exception.

这篇关于最终阻止真正需要清理代码(如关闭流)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆