Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Use the right exception

Avoid throwing the generic java.lang.Exception or java.lang.RuntimeException. Find an exception that fits the situation or subclass exception and create your own. This allows the exception to be more meaningful and easier to maintain. It also avoids logic bugs that can occur when a too-general exception is thrown. Take for example, the following code:

try {
 Connection con = getConnection();
  PrepareStatement ps = con.prepareStatement("select * from exampleTable");
  ResultSet rs = ps.executeQuery();
  if (rs.next()) return DATA_IN_TABLE;
  else return NO_DATA_IN_TABLE;
} catch (Exception e) {
  System.err.println("Error accessing the database");
  return DATABASE_ERROR;
}

In this example, any error in the try block will lead the maintainer to believe that there is a problem with the database. Imagine, for instance, that an error exists in the getConnection() method call whereby it silently returns a null. A NullPointerException would be thrown, but it would appear to be a database error. If, however, the catch block only captured SQLException, the NullPointerException would escape the catch block and make it very clear that there is an unexpected situation.

  • + Share This
  • 🔖 Save To Your Account