Reputation: 49
Should I catch all exceptions (catch Throwable) when closing a resource like a JDBC resource (like a database connection) in a finally block (like the Spring Framework does org.springframework.jdbc.support.JdbcUtils.closeConnection(Connection con) ) or should I only catch SQLException and let any other unchecked exception thrown from close() confuse the original caller by masking an exception in the try section or throwing an exception when everything in my code went OK, instead of just logging that JDBC driver exception like the Spring Framework does?
Upvotes: 3
Views: 976
Reputation: 13475
Please note that Spring has serious excuses to do so:
"// We don't trust the JDBC driver: It might throw RuntimeException or Error.
". You add a comment to a code when you do something that needs explanations, in this case - violating best practices.String
, and to fulfill some more strict restrictions. Otherwise, it won't survive catching an OutOfMemoryError
or VirtualMachineError
.Don't catch Throwable
. Error
, its subclass, says: "An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch."
Moreover, it's even not normally reasonable to catch an Exception
. Even if close()
threw, for example, an IndexOutOfBoundsException
, you want to announce this as loud as possible to your team, your customer and his SE, for all of them should know that the JDBC driver cannot be trusted. close()
is only allowed to throw SQLException, period.
Because, well, database is their main asset, and we NEED a working drivers.
Only as a last resort, like in this Spring example, when you KNOW you will be working with faulty drivers, this is acceptable.
Upvotes: 1
Reputation: 49
After some research I found out that the most sensible thing to do is to catch any exception when closing resources as you do not want your method to throw when the close throws an exception. Spring Framework JdbcUtils does the right thing. Some amateur programmers think that Errors are such grave Exceptions that should shutdown everything, but if you are running in servlet context these Errors will not shut down the application server see, for example, Tomcat StandardWrapperValve, so you should do the same and not let any Error when closing a resource make your method fail.
Upvotes: 0