In certain cases there are chances where the exceptions are not caught properly.
I thought of solving this issue by writing a small utility in Java 5
public static void closeResources(Object... resources) {
for (Object resource : resources) {
if (resource != null) {
try {
// Fix to avoid already closed exception
if (resource instanceof Connection) {
Connection con = (Connection) resource;
if (!con.isClosed()) {
con.close();
}
} else {
Method closeMethod = (resource.getClass()).getMethod(
"close", null);
closeMethod.setAccessible(true);
closeMethod.invoke(resource, null);
}
} catch (Exception e) { // ByPassing all the exception
logger.info(e.getMessage(), e);
}
}
}
}
You can use these method as with any of the DB resources.
Some examples are
closeResources(rs);
closeResources(rs,pstmt);
closeResources(rs,pstmt,connection)