问题描述
每当我需要使用Java获取资源然后保证释放该资源(可能会引发异常)时,我都会使用以下模式:
Whenever I need to acquire a resource in Java and then guarantee that the resource is released, where an exception might be thrown, I use the following pattern:
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
}
例如,如果我需要数据库连接,并且使用或关闭该连接会引发异常,请编写以下代码:
For example, if I need a database connection, and using or closing the connection can throw an exception, I write the following code:
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,因为我有义务捕捉关闭数据库连接时可能抛出的(可能)异常,而且我永远也不知道如何处理该异常.
I don't like just doing a simple try-catch-finally because I am obligated to catch the (possible) exception that can be thrown when the database connection is closed, and I am never sure how to handle that one.
是否有更好的模式来处理这种情况?
Is there a better pattern for handling this situation?
推荐答案
我个人使用以下模式:
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())难以处理且应在更高级别处理时,我将使用这种模式.
or similar to that. This pattern doesn't lose the exception, but makes your code a lot cleaner. I use this pattern when the exception being caught in the finally clause (in this case close()) is difficult to deal with and should be dealt with at a higher level.
清洁工仍将使用贷款模式.
Cleaner still is to use the loan pattern.
这篇关于Java try-finally内部try-catch模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!