java - Try-catch-finally 然后再次 try catch

标签 java exception-handling try-catch-finally

我经常遇到这样的情况:-

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/

相关文章:

java - 如何使用 GW EPL 命令和 java 在 TSC 打印机上打印图像

java - 使用 Selenium Java 无法按名称包含找到复选框元素

c++ - boost 异常

c# - try catch finally block 的点?

c# - 通过catch block 从函数返回,finally block 会发生什么?

iphone - @try - Objective-C 中的 catch block

java - OpenApi 3 codegen java如何实现

java - 是什么阻止使 Cloneable 成为像 StringBuilder 这样的可变对象?

php - php7中的错误和异常处理

swift - 从没有 throws 的继承函数中抛出异常