Java try finally内部的try-catch模式
每当我需要获取Java中的资源,然后保证该资源被释放时(可能会引发异常),我都会使用以下模式:Java try finally内部的try-catch模式,java,exception-handling,Java,Exception Handling,每当我需要获取Java中的资源,然后保证该资源被释放时(可能会引发异常),我都会使用以下模式: try { Resource resource = null; try { resource = new Resource(); // Use resource } finally { if (resource != null) { // release resource } } } catch (Exception ex) { // h
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
}
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
}
}
例如,如果我需要一个数据库连接,并且使用或关闭连接可能引发异常,我将编写以下代码:
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,因为我有义务捕获数据库连接关闭时可能抛出的(可能的)异常,而且我永远不知道如何处理该异常
是否有更好的模式来处理这种情况?如果您不知道如何处理异常,则不应捕获异常。可以解决您的问题 例如:
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);
}
就我个人而言,我使用以下模式:
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
}
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())中捕获的异常很难处理并且应该在更高级别上处理时,我使用这种模式
更干净的方法仍然是使用贷款模式。为什么不在普通异常中添加finally子句。(本例中为SqlException…)类似,但不是完全重复:我不喜欢在关闭资源之前必须检查资源是否为空。我宁愿在try块之外创建资源并避免所有这些。此外,关闭过程中抛出的异常也非常无用,只需记录它们并继续。如果它已经用
IOUtils.closequity(closeable)关闭,我看不出这里的closeable.close()
有什么意义代码>。此外,这是吞咽例外。也许让它在更高的层次上传播和处理会更好。很明显,如果你不知道该怎么做,有两种选择。吞咽或传播:)我之前的例子是吞咽异常。这是记录和吞咽。好多了:)。谢谢@Xavi.Hahah,是的:)也谢谢你给我看closequity()
!