繁体   English   中英

Java try-finally在try-catch模式中

[英]Java try-finally inside try-catch pattern

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

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

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);
    }

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

  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())难以处理时,我使用此模式,应该在更高级别处理。

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

如果您不知道如何处理它们,则不应捕获异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM