Java try-finally 里面的 try-catch 模式

标签 java exception-handling

每当我需要在 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,因为我有义务捕获数据库连接关闭时可能抛出的(可能的)异常,而我永远不确定如何处理该异常。

是否有更好的模式来处理这种情况?

最佳答案

就我个人而言,我使用以下模式:

  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())中捕获的异常难以处理并且应该在更高级别处理时,我使用此模式。

Cleaner还是使用借贷模式。

关于Java try-finally 里面的 try-catch 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7433228/

相关文章:

c++ - 处理超出范围的索引

java - 捕获错误的异常

java - Lucene 3.6 索引编写器

java - JComboBox as Jtable CellEditor with Overriden stopCellEditing modifies wrong table cell

Epson热敏票据打印机的Java控制

java - 我们是否应该以多个声明为代价来本地化作用域变量

java - 如何使用Java检查链表是否已满?

c# - 最后在 C# 中阻塞

java - jvm异常捕获

java - SonarQube 错误 : Refactor this method to throw at most one checked exception