Java try-finally在try-catch模式中

Ral*_*lph 3 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
}
Run Code Online (Sandbox Code Playgroud)

例如,如果我需要数据库连接,并且使用或关闭连接可能会抛出异常,我会编写以下代码:

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
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢只是做一个简单的try-catch-finally因为我有义务捕获数据库连接关闭时可能抛出的(可能的)异常,而且我永远不知道如何处理那个.

处理这种情况有更好的模式吗?

Sah*_*hoo 8

IOUtils.closeQuietly() 可以解决你的问题.

例:

    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);
    }
Run Code Online (Sandbox Code Playgroud)


Mat*_*ell 8

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

  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
  }
}
Run Code Online (Sandbox Code Playgroud)

或类似的.此模式不会丢失异常,但会使您的代码更清晰.当finally子句中捕获的异常(在本例中为close())难以处理时,我使用此模式,应该在更高级别处理.

清洁工仍然是使用贷款模式.