我们为什么要使用最后的方块?
据我所知,以下两个代码片段将具有相同的目的。为什么会有区块?finally
代码 A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
代码 B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
据我所知,以下两个代码片段将具有相同的目的。为什么会有区块?finally
代码 A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
代码 B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
Throwable
一个块确保无论你退出该块(模出一些显式中止整个过程的方法),它都会被执行。这对于资源的确定性清理非常重要。finally
请注意(至少在 Java 中,可能在 C# 中也是如此),也可以有一个没有 的块,但有一个 .当块中发生异常时,块中的代码将在异常被抛出更高位置之前运行:try
catch
finally
try
finally
InputStream in = new FileInputStream("somefile.xyz");
try {
somethingThatMightThrowAnException();
}
finally {
// cleanup here
in.close();
}