Best practices for creating (Java) exceptions:

1. When deciding on checked exceptions vs. unchecked exceptions, ask yourself "What action can the client code take when the exception occurs?". Use unchecked exception when the client code cannot do anything, otherwise use checked exception. Use a checked exception for conditions client code can reasonably be expected to handle.

2. Why checked exceptions?

  • From the Java Language Specification: "This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled".
  • If you are throwing an exception for an abnormal condition that you feel client programmers should consciously decide how to handle, throw a checked exception.
  • Unchecked exceptions indicate software bugs.
  • Precisely because unchecked exceptions usually represent software bugs, they often can't be handled somewhere with more context.

3. Preserve encapsulation. Never let implementation-specific checked exceptions escalate to the higher layers. For example do not propagate SQLException from data access code to the business objects layer. Most of the time client code cannot do anything about SQLExceptions, do not hesitate to convert them into unchecked exceptions.

4. Try not to create new custom exceptions if they do not have useful information for client code.

5. You want each different kind of abnormal condition to be catchable in its on catch clause, to separate the handlers. Use inheritance relationships to enable a single catch clause to catch all flavors. Catch clauses catch exceptions based on type.

6. Document all exceptions.

  • No labels