Recently, I have been facing a problem with throwing exception in JDBC topic.
I synchronized Connection object by using 2 synchronized methods: getConnection() and releaseConnection(). Then another method which removes a row from database as follow:
public void removeItem(int itemID) throws ItemNotFound {
PreparedStatement ps = null;
String query = "DELETE * FROM Student.Book WHERE id = ?";
getConnection();
try {
ps = con.prepareStatement(query);
ps.setInt(1, bookID);
ps.executeUpdate();
} catch (SQLException sqle) {
this.close(null, null, ps); // method to close PreparedStatement and ResultSet
releaseConnection();
throw new BookNotFoundException("Book not found!");
} finally {
this.close(null, null, ps);
releaseConnection();
}
}
Everything works well if no exception occurs. In case exception occurs, in catch block after releaseConnection() method, throw new BookNotFoundException(“Book not found!”) hangs up!! If i comment releaseConnection() method then it throws normally?
You’re releasing the connection twice. The
finallyblock will always run, even if acatchblock runs. My guess is it’s doing thethrow, then running thefinallyblock, which tries to release the connection a second time. I’m not sure how you implementedreleaseConnection(), but if that blocks when the connection has already been released then this would explain the problem.I think if you just remove the
closeandreleaseConnectionfrom the catch block it should work fine.