Exception best practices
Favor RuntimeExceptions over checked exceptions – follow Hibernate’s example. This allows clients to choose what to do.
Always declare throws on methods even for runtime exceptions - for clarity, not necessary in tests
Always include @throws in the JavaDoc for each exception and state under what circumstances it throws the exceptions
Always include the details (state) related to the cause of the exception in the message - this will help others debug the issue (it isn’t really for us the developers, it’s for the poor guys/gals on the front line who have to debug our broken s$*t) – utilize String.format and include what was being processed and all state that might be helpful in understanding the issue – beware of possible NPEs in String.format arg method calls. And yes this takes time and requires thought on how to clearly convey the information; however it is incredibly useful, sometimes even for us developers.
Always remember to wrap any source exceptions in your own exception processing.
In worker threads – generally catch, log, convey (if necessary), and swallow all exceptions – generally you don’t want your worker threads terminating as they are often loops which will have additional work to process
In loops consider if you should aggregate exceptions and continue processing – do you really want to stop after an exception or process as much as possible collecting the exceptional issues to be returned later as a set
Always declare throws on methods even for runtime exceptions - for clarity, not necessary in tests
Always include @throws in the JavaDoc for each exception and state under what circumstances it throws the exceptions
Always include the details (state) related to the cause of the exception in the message - this will help others debug the issue (it isn’t really for us the developers, it’s for the poor guys/gals on the front line who have to debug our broken s$*t) – utilize String.format and include what was being processed and all state that might be helpful in understanding the issue – beware of possible NPEs in String.format arg method calls. And yes this takes time and requires thought on how to clearly convey the information; however it is incredibly useful, sometimes even for us developers.
Always remember to wrap any source exceptions in your own exception processing.
In worker threads – generally catch, log, convey (if necessary), and swallow all exceptions – generally you don’t want your worker threads terminating as they are often loops which will have additional work to process
In loops consider if you should aggregate exceptions and continue processing – do you really want to stop after an exception or process as much as possible collecting the exceptional issues to be returned later as a set
Comments