How to correctly close resources?

泪湿孤枕 提交于 2019-12-11 05:17:23

问题


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

Let's say I have method like this

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

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?


回答1:


public void foo() throws Exception e {

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



回答2:


Close it in finally block. All resources opened should be released/closed.
See this for more - http://www.ibm.com/developerworks/java/library/j-jtp03216.html




回答3:


Modification to nos answer. You actually may initialize stmt before try block. That way there is no need to see if it's null, so this just suffice:

public void foo() throws Exception e {

  final Statement stmt = createStatemnt( );

  try {
    doSomething(stmt);
  } finally {
    stmt.close();
  }
}



回答4:


Yes, you can throw the exception further

try {
   stmt = createStatement();
   doSomething(stmt);
}
 catch (Exception e) {
    throw e;
}
finally {
   if(stmt != null) 
      stmt.close();
}


来源:https://stackoverflow.com/questions/2362686/how-to-correctly-close-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!