1

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?

kane77
  • 591
  • 1
  • 6
  • 20

4 Answers4

6
public void foo() throws Exception e {

  Statement stmt = null ; 
  try {
    stmt = createStatement();
    doSomething(stmt);
  } finally {
    if(stmt != null) 
      stmt.close();
  }
}
nos
  • 223,662
  • 58
  • 417
  • 506
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

Padmarag
  • 7,067
  • 1
  • 25
  • 29
1

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();
  }
}
Community
  • 1
  • 1
Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
-1

Yes, you can throw the exception further

try {
   stmt = createStatement();
   doSomething(stmt);
}
 catch (Exception e) {
    throw e;
}
finally {
   if(stmt != null) 
      stmt.close();
}
HeDinges
  • 4,367
  • 4
  • 30
  • 28
  • no need to add that catch block as the method already declares that throws Exception. You can have a try-finally block with no catch – Lombo Mar 02 '10 at 11:38
  • Why would you bother catching and rethrowing here? try ... finally works fine without a rethrow. http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.20.2 – JUST MY correct OPINION Mar 02 '10 at 11:40
  • I missed out the throws in the signature, I thought the question was If it was valid to throw an exception further in the catch block. – HeDinges Mar 02 '10 at 13:19