0 java connection garbage-collection stream try-catch-finally
这是一些java代码.
public class SomeClass {
private Connection connection;
public SomeClass(Connection c) {
connection = c;
}
public void someWork(){
Connection c;
try {
// do something
} catch (Exception e) {
// some exception code
} finally {
if (conn != null){
try {c.close();} catch (Exception e) {}
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
但我不喜欢代码
if (conn != null){
try {c.close();} catch (Exception e) {}
}
Run Code Online (Sandbox Code Playgroud)
所以我认为代码
...catch (Exception e) {
// some exception code
} finally {
c = null;
}
Run Code Online (Sandbox Code Playgroud)
但我看到'流对象不是垃圾收集'.
我不会在finally块中使用try-catch语句.请给我另一种方式.
只需创建一个静态实用方法:
private static void closeQuietly(final Connection conn)
{
if (conn == null)
return;
try {
conn.close();
} catch (WhateverException ignored) {
}
}
Run Code Online (Sandbox Code Playgroud)
然后
conn = whatever(); // create it there, not in the try block
try {
// work
} catch (WhateverException e) {
// whatever
} finally {
closeQuietly(conn);
}
Run Code Online (Sandbox Code Playgroud)
但最终,无论如何,你将在finally块中使用try/catch.
请注意,捕获Exception是一个坏主意.捕获特别提出的异常conn.close().捕捉Exception意味着你也能抓住所有人RuntimeException; 这是一件坏事(tm).
如果您使用Guava,您也可以使用Closeables.closeQuietly(),它与上面的代码几乎完全相同.您也可以看看Closer,这非常有趣.
最后(双关语):如果您使用Java 7,请使用try-with-resources语句(请参阅参考资料AutoCloseable):
try (
conn = whatever();
) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
266 次 |
| 最近记录: |