首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java try-finally在try-catch模式中

Java try-finally在try-catch模式中
EN

Stack Overflow用户
提问于 2011-09-15 23:14:45
回答 3查看 4.5K关注 0票数 4

每当我需要在Java中获取资源,然后保证释放该资源时,可能会抛出异常,我就使用以下模式:

代码语言:javascript
复制
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
}

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

代码语言:javascript
复制
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,因为我有责任捕捉当数据库连接关闭时可能抛出的(可能)异常,而我从来不确定如何处理这个异常。

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-09-15 23:20:26

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

代码语言:javascript
复制
  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())很难处理并且应该在更高级别上处理时,我使用此模式。

更干净的仍然是使用贷款模式。

票数 8
EN

Stack Overflow用户

发布于 2011-09-15 23:18:31

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

示例:

代码语言:javascript
复制
    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);
    }
票数 8
EN

Stack Overflow用户

发布于 2011-09-15 23:18:29

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7433228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档