Moh*_*eem 82 .net java finally
据我所知,以下两个代码片段都将起到同样的作用.为什么要有finally
块?
代码A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
Run Code Online (Sandbox Code Playgroud)
代码B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 133
Throwable
...)一个finally
块可以确保但是你退出该块(模明确中止整个过程的几个方法),它会被执行.这对于确定性清理资源非常重要.
Jes*_*per 11
注意(至少在Java中,也可能在C#中),也可以有一个try
没有a 的块catch
,但是有一个finally
.当try
块中发生异常时,块中的代码在finally
异常被抛出之前运行:
InputStream in = new FileInputStream("somefile.xyz");
try {
somethingThatMightThrowAnException();
}
finally {
// cleanup here
in.close();
}
Run Code Online (Sandbox Code Playgroud)
小智 7
无论在try或catch块中发生什么,您可能希望将所需的代码放到执行中.
此外,如果您使用多个catch并且如果您想要放置一些常用于所有catch块的代码,那么这将是一个放置的位置 - 但您无法确定try中的整个代码是否已执行.
例如:
conn c1 = new connection();
try {
c1.dosomething();
} catch (ExceptionA exa) {
handleexA();
//c1.close();
} catch (ExceptionB exb) {
handleexB();
//c1.close();
} finally {
c1.close();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15999 次 |
最近记录: |