尝试-捕捉-最后,然后再次尝试捕捉
2022-09-01 09:40:43
我经常遇到这样的情况:-
try{
...
stmts
...
}
catch(Exception ex) {
...
stmts
...
} finally {
connection.close // throws an exception
}
这仍然需要尝试 - 最后在里面捕捉块。
克服这个问题的最佳实践是什么?
我经常遇到这样的情况:-
try{
...
stmts
...
}
catch(Exception ex) {
...
stmts
...
} finally {
connection.close // throws an exception
}
这仍然需要尝试 - 最后在里面捕捉块。
克服这个问题的最佳实践是什么?
编写一个类,其中包含捕获和记录此类异常的方法,然后根据需要使用。SQLUtilsstatic 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接口进行了扩展,虽然上面的代码回答了原始问题,但如果你直接针对JDBC API编写代码,它现在可以结构化:java.lang.AutoCloseable
try (
Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(...);
ResultSet resultSet = statement.executeQuery()
)
{
...
}
正如其他人所提到的,静态实用程序是要走的路。要添加的一件事 - 如果你处于世界中,那么有一个有用的接口可以达到这个目的 - java.io.CloseablecloseQuietlyjava.iojava.sql
实现此接口中的所有数据源和接收器 - 所有流、通道、写入器和读取器。这样,您可以创建单个实用程序来处理相同的“异常 on close()”问题,而无需许多过载版本。java.io
例如:
public class IoUtils {
public static closeQuietly (Closeable closeable) {
try {
closeable.close();
} catch (IOException logAndContinue) {
...
}
}
}