我经常遇到这样的情况:-
try{
...
stmts
...
}
catch(Exception ex) {
...
stmts
...
} finally {
connection.close // throws an exception
}
finally 内部仍然需要一个 try-catch block 。
克服这个问题的最佳做法是什么?
最佳答案
编写一个 SQLUtils
类,其中包含捕获和记录此类异常的 static closeQuietly
方法,然后酌情使用。
你最终会得到如下内容:
public class SQLUtils
{
private static Log log = LogFactory.getLog(SQLUtils.class);
public static void closeQuietly(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLExcetpion e)
{
log.error("An error occurred closing connection.", e);
}
}
public static void closeQuietly(Statement statement)
{
try
{
if (statement!= null)
{
statement.close();
}
}
catch (SQLExcetpion e)
{
log.error("An error occurred closing statement.", e);
}
}
public static void closeQuietly(ResultSet resultSet)
{
try
{
if (resultSet!= null)
{
resultSet.close();
}
}
catch (SQLExcetpion e)
{
log.error("An error occurred closing result set.", e);
}
}
}
您的客户端代码将类似于:
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try
{
connection = getConnection();
statement = connection.prepareStatement(...);
resultSet = statement.executeQuery();
...
}
finally
{
SQLUtils.closeQuietly(resultSet);
SQLUtils.closeQuietly(statment);
SQLUtils.closeQuietly(connection);
}
更新: 从 Java 7 开始,各种 JDBC 接口(interface)扩展了 java.lang.AutoCloseable
并且上面的代码回答了最初的问题,如果您直接编写代码针对 JDBC API,现在可以对其进行结构化:
try (
Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(...);
ResultSet resultSet = statement.executeQuery()
)
{
...
}
关于java - Try-catch-finally 然后再次 try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1335812/