每当我需要在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,因为我有责任捕捉当数据库连接关闭时可能抛出的(可能)异常,而我从来不确定如何处理这个异常。
有没有更好的模式来处理这种情况?
发布于 2011-09-15 23:20:26
就我个人而言,我使用以下模式:
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())很难处理并且应该在更高级别上处理时,我使用此模式。
更干净的仍然是使用贷款模式。
发布于 2011-09-15 23:18:31
IOUtils.closeQuietly()可以解决你的问题。
示例:
Closeable closeable = null;
try {
closeable = new BufferedReader(new FileReader("test.xml"));
closeable.close();
} catch (IOException e) {
// Log the exception
System.err.println("I/O error");
} finally {
// Don't care about exceptions here
IOUtils.closeQuietly(closeable);
}发布于 2011-09-15 23:18:29
如果您不知道如何处理异常,就不应该捕获它们。
https://stackoverflow.com/questions/7433228
复制相似问题