Java Exception Handling

Modules need dependencies of other modules only because of their exception classes
From validation/ItemValidating:

From importmanager/ImportHandler:

Sometimes, excessive stacktraces are shown, even without useful information
Example from coreservices:

Logger.error, System.out and e.printStackTrace are mixed up happily
see above

No distinction between exceptions and errors/checked and unchecked exceptions
Compare Exception and Error

Different interface boundaries handle exceptions differently

 * Java --> Java exception handling
 * EJB --> partly controlled Java exception handling (RemoteException, EJBException)
 * SOAP --> eventually generating exception classes
 * REST --> error communication via status codes

Distinguish between repairable exceptions and errors
Decide whether your module is able to fix the exception (take default values, look somewhere else, try again, ...) or not.

Only catch repairable exceptions

 * If an exception is somehow repairable, try this in the catch-block
 * If the repairing is critical in some respect, at least log a warning message (e.g. logger.warn("Value for xyz not found, taking default value"))
 * If repairing fails treat the exception as an error

Inside a module, prefer unchecked exceptions
Turn checked exceptions from third-party modules into unchecked exceptions, e.g.

Inside a module, always throw errors up as they are (alternatively)
Do not care for exceptions at all, just declare them to be thrown, e.g.

When catching exceptions, log appropriately

 * use log4j, not System.out
 * use the two-argument methods:
 * logger.error("Error geting server.name property", ex);
 * logger.error("Error geting server.name property"); --> Exception information is lost
 * logger.error(ex); --> Only ex.toString is logged, other exception information is lost
 * when an exception is rethrown, do not log (except when throwing out of the module)

Throw self-defined exceptions that are defined inside the throwing module

 * For exceptions concerning the logic of the module, exceptions should be defined and checked
 * No third module should be necessary to define these exceptions

Between modules, throw only generic exceptions
e.g. IllegalArgumentException, IllegalStateException, RuntimeException

Open questions

 * Shall interfaces define checked exceptions?
 * If so, shall self-defined exceptions be used?

Links

 * OnJava: Best Practices for Exception Handling
 * IBM: Best practices in EJB exception handling
 * Sun: Three Rules for Effective Exception Handling