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.