每当我需要在 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())中捕获的异常难以处理并且应该在更高级别上处理时,我使用此模式。
清洁工仍然是采用贷款模式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)