genjava / tips / exception rules

Java Rules for Exceptions

  1. Never throw 'Exception'.
  2. Never catch 'Error', 'RuntimeException' or 'Throwable'.
  3. Never catch 'Exception' unless you're forced to by a poor API.
  4. Don't allow exception's to be thrown beyond their semantic scope. For example, don't throw DatabaseException all the way to your GUI, catch the DatabaseException at the correct level and throw a new exception that is relevant to that area, ie) ObjectSavingException. Hide the fact the database is there.
  5. Use an easy naming convention for exception classes. Advice is to use the capital letters of the exception. So MissingResourceException has a variable name of 'mre' and NumberFormatException is 'nfe'.
  6. If reporting an error, always print the stack trace.