Understanding exception handling best practices

Having good exception handling is important to ensure the following:

  • Your users know who to contact to seek help or support.
  • Your developers/support team have the information to solve the problem.

In the Java world, we have two types of exceptions:

  • Checked exceptions: When a service method throws this exception, all the consumer methods should either handle or throw the exception.
  • Unchecked exceptions: The consumer method is not required to handle or throw the exception thrown by the service method.

RuntimeException and all its subclasses are unchecked exceptions. All other exceptions are checked exceptions.

Checked exceptions can make your code hard to read. This can be seen in the following example:

    PreparedStatement st = null;
try {
st = conn.prepareStatement(INSERT_TODO_QUERY);
st.setString(1, bean.getDescription());
st.setBoolean(2, bean.isDone());
st.execute();
} catch (SQLException e) {
logger.error("Failed : " + INSERT_TODO_QUERY, e);
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// Ignore - nothing to do..
}
}
}

The declaration of the execute method in the PreparedStatement class is as follows:

    boolean execute() throws SQLException

SQLException is a checked exception. So, any method that calls the execute() method should either handle the exception or throw it. In the preceding example, we handle the exception using a try-catch block.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset