Reputation: 1499
I have a code like this.
try {
st = Session.getDbConnection().createStatement();
delSt = Session.getDbConnection().createStatement();
rs = st.executeQuery("SELECT msg_id,message,mobile_no FROM sms");
while (rs.next()) {
delSt.executeUpdate("DELETE FROM sms WHERE msg_id = '" + rs.getString(1) + "'");
System.out.println("Message sent");
}
Session.getDbConnection().commit();
} catch (Exception ex) {
if (ex.getMessage().startsWith("error occurred at recursive")){
}
else{
logger.error(ex.getMessage(), ex);
}
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (delSt != null) {
delSt.close();
}
} catch (Exception ex1) {
logger.error(ex1.getMessage(), ex1);
ex1.printStackTrace();
}
try {
if (!Session.getDbConnection().isClosed()) {
Session.getDbConnection().close();
}
} catch (Exception ex1) {
logger.error("ERROR:Closing Database Connection:" + ex.getMessage(), ex);
}
} finally {
}
Now In this case I want to ignore/avoid the exception "error occurred at recursive SQL level 1" for log. But I want to log other than this exception. What's wrong with my code. Thanks
Upvotes: 0
Views: 114
Reputation: 272257
I don't think
if (ex.getMessage().startsWith("error occurred at recursive")){
}
is particularly safe. You're assuming the exception message is never null (!) and then performing a comparison on the exception message. I would rather catch specific classes of exception e.g.
catch (SQLException e)
and filter on the class itself. You can also make use of the error codes returned by the database. These are database-vendor specific, note. See SQLException doc for more details and in particular the getErrorCode()
method (I'm assuming you're actually catching SQLExceptions
here, but the principle is wider)
Other comments. You should be closing the resultset/statements/connection outside the exception handling and in your finally
block. You need to free those resources regardless of exceptions/success. Perhaps check out DBUtils.closeQuietly() to do this safely and concisely.
Upvotes: 2