On Exceptions
- Try to avoid exceptions. Use the language features and proper design in order to achieve it.
- Use runtime exceptions, wrap methods with checked exceptions and turn them in at runtime.
- Try to use standard exceptions.
- Make your exceptions specific and descriptive.
- Catch the most specific exception first.
- Do not catch on Exception.
- But catch on Exception on the boundaries of your API. Have complete control over what comes out to the world.
- Create a hierarchy of exceptions that match the layers and functionalities of your application.
- Throw exceptions at the proper abstraction level. Catch an exception and throw a higher level one as you move from layer to layer.
- Pass the complete history of exceptions when rethrowing by providing the exception in the constructor of the new one.
- Think of the try-catch-finally block as a transaction. Make sure you leave your program in a valid state when something goes wrong.
- Catch exceptions when you can handle it.
- Never have empty catch clauses.
- Log an exception when you handle it.
- Have a global exception handling service and have a strategy on how you handle errors.