bool closeCalled = false;
OutputStream stream = ...;
try {
stream.write(...);
closeCalled = true;
stream.close();
} catch (IOException e) {
if (!closeCalled) {
// TODO: Add another try/catch here? What do we want to
// do if this throws?
stream.close();
}
throw e;
}
与之相比:
OutputStream = ...;
try {
stream.write(...);
} finally {
// TODO: Still need to work out what to do if this throws.
stream.close();
}
what is the need of finally block when we can close files and all in catch block. whatever thing we are closing or clearing in the finally block can it be done inn catch block
# 1 楼答案
无论是否引发异常,通常都希望执行相同的清理操作。用catch blocks执行只是是很痛苦的,尤其是如果你想确保只调用
close()
一次,即使那抛出。你最终会得到:与之相比:
或者最好:
就个人而言,我认为最后一个例子是迄今为止最干净的——你真的想要到处都是第一块代码吗?哦,这是一个简单的例子——我们只捕捉到一个例外。想象一下,在每个
catch
子句中重复该代码,如果有多种退出try
块的方法,也会对其中的每一个重复close调用。。。哎呀此外,正如尼古拉斯在评论中指出的那样,还有所有未经检查的例外情况,你都无法捕捉到(捕捉和重新捕捉可能会很痛苦)。从根本上说,“无论发生什么,我只想清理我的资源”的原则是非常非常有说服力的
# 2 楼答案
只有当
try
块中出现异常时,才会执行catch
块当你想每次都做一些操作,比如清理,你需要在
finally
块中写代码Finally将始终执行,catch block不会始终执行
考虑下面的例子,
您打开了一个文件,并试图复制到
try
块中的另一个文件,如果代码执行良好,catch块将不会执行,您将以不关闭文件结束