Exception handling

There are 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 cumbersome to read. Take a look at 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 shown 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 are handling 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