I'm posting this here since it involves a connection object and a "connection is closed error" which led me to this puzzling behavior. This is the code for a DAO which is called from a servlet.
I set breakpoints on this and stepped through it. Everything works correctly and the value of urlResult is the single record expected from the database, but as soon as the while loop ends, the code jumps to the return line and the finally never executes. When it reaches the return line, the values are as follows:
Up to this point, no exceptions have been thrown, but the value of connection is odd because it's null, but it's not really null as you'll see in a moment.
One more step and the above method returns to the servlet at the "url=urlDAO.getSingleURL(dept)" line below.
In this code the finally block does run, but it tries to close the connection because of the odd null-but-not-null value of the connection and of course throws a SQLException of "Connection is closed".
What am I doing wrong? Maybe I shouldn't be passing a reference to the connection from servlet to DAO but rather have the DAO create the connection? And why is the finally block in the DAO not running at all? I didn't think that was possible except under rare circumstances such as killing a thread or doing a system.exit in the try block.
Thanks for any suggestions.
"There is no reason for any individual to have a computer in his home" ~ Ken Olson, Co-founder of DEC, 1977
More info...I removed the e.printStackTrace() lines from the finally block, because NetBeans was complaining about them, so the code looks like this and now the finally block runs. Why?
However, I still have the issue with the finally block in the servlet trying to close the null-but-not-null connection and throwing an error. Can anyone explain that one?
Is there a better way to close the connection instead of the "if(conn != null)" test?
You can use Connection.isClosed() along with the null check. The more common code, though, is what you have where you check for null, attempt to close regardless, and exit. Trying to close an already closed connection and throwing a swallowed exception doesn't usually cause a problem in practice, whereas failing to close a connection definitely can cause issues. In other words, when it comes to closing connections it's better to be extra cautious than forgetful.