每当我需要在 Java 中获取资源然后保证资源被释放时,可能会抛出异常,我使用以下模式:
try {
Resource resource = null;
try {
resource = new Resource();
// Use resource
} finally {
if (resource != null) {
// release resource
}
}
} catch (Exception ex) {
// handle exceptions thrown by the resource usage or closing
}
比如我需要一个数据库连接,使用或者关闭连接都会抛出异常,我写如下代码:
try {
Connection connection = null;
try {
connection = ... // Get database connection
// Use connection -- may throw exceptions
} finally {
if (connection != null) {
connection.close(); // This can also throw an exception
}
}
} catch (SQLException ex) {
// handle exceptions thrown by the connection usage or closing
}
我不喜欢只做一个简单的 try-catch-finally,因为我有义务捕获数据库连接关闭时可能抛出的(可能的)异常,而我永远不确定如何处理该异常。
是否有更好的模式来处理这种情况?
最佳答案
就我个人而言,我使用以下模式:
Connection connection = null;
try {
connection = ... // Get database connection
// Use connection -- may throw exceptions
} finally {
close(connection);
}
private void close(Connection connection) {
try {
if (connection != null) {
connection.close(); // This can also throw an exception
}
} catch (Exception e) {
// log something
throw new RuntimeException(e); // or an application specific runtimeexception
}
}
或类似的。这种模式不会丢失异常,但会使您的代码更清晰。当在 finally 子句(在本例中为 close())中捕获的异常难以处理并且应该在更高级别处理时,我使用此模式。
Cleaner还是使用借贷模式。
关于Java try-finally 里面的 try-catch 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7433228/