如何正确关闭资源? [英] How to correctly close resources?

查看:102
本文介绍了如何正确关闭资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些方法都可以传播异常,然后在一个地方进行处理,但是我意识到了一些事情.

I have methods that all propagate exceptions and then I have handling on one place, however I realized something.

假设我有这样的方法

public void foo() throws Exception e {
  Statement stmt = createStatement();
  doSomething(stmt);
  stmt.close();
}

我的问题是,如果doSometing()方法引发异常,该语句将不会关闭,但是我不想在那里处理异常.尝试并捕获只会抛出异常并最终关闭语句的正确方法吗?

My issue is that if exception is thrown by doSometing() method the statement will not be closed, but I don't want to handle exception there. Is the right approach to have try and catch that only rethrows exception and finally to close statement?

推荐答案

public void foo() throws Exception e {

  Statement stmt = null ; 
  try {
    stmt = createStatement();
    doSomething(stmt);
  } finally {
    if(stmt != null) 
      stmt.close();
  }
}

这篇关于如何正确关闭资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆