Search code examples
javahadoophbasetry-catch

Closing DB connection on finally in try catch


If we are opening a database connection in a method and we want to ensure that the connection is closed in the case of an exception, we can put connection.close() in the finally block. My question is, what if closing the connection can also throw an exception? How should this code look?

try {
    conn.open();
    //Do stuff with database
} catch (Exception e) {
    e.printStackTrace();
} finally {
    conn.close(); //Can potentially throw exception.
}

I have been including a "throws Exception" as part of the method. Example:

public void doSomethingWithDB() throws Exception {
    //Method Body
}

If an exception is thrown on conn.close(), in most cases is the connection automatically closed? Or will streams remain open?

For more context, I am using Apache Phoenix with HBase and have run into this question as I am trying to be a more safe coder and not accidentally keep streams open to HBase.


Solution

  • An exception raised from close means that something about the connection shutdown did not work. So chances are that not everything has been cleaned up properly. However, there is probably not much you can do about that at that point.

    Usual practice is to have a closeQuietly helper method that tries to close as much as possible and catches any exceptions (possibly logging them). Your application would then soldier on, just as if the close worked.

    Note that such a helper is even necessary when you use a try-with-resources block.