Friday, April 28, 2017

Java Exception Handling Best Practices

Java Exception Handling Best Practices :

  1. Never swallow the exception in catch block
  2. Declare the specific checked exceptions that your method can throw
  3. Do not catch the Exception class rather catch specific sub classes
  4. Never catch Throwable class
  5. Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost
  6. Either log the exception or throw it but never do the both
  7. Never throw any exception from finally block
  8. Always catch only those exceptions that you can actually handle
  9. Don't use printStackTrace() statement or similar methods
  10. Use finally blocks instead of catch blocks if you are not going to handle exception
  11. Remember "Throw early catch late" principle
  12. Always clean up after handling the exception
  13. Throw only relevant exception from a method
  14. Never use exceptions for flow control in your program
  15. Validate user input to catch adverse conditions very early in request processing
  16. Always include all information about an exception in single log message
  17. Pass all relevant information to exceptions to make them informative as much as possible
  18. Always terminate the thread which it is interrupted
  19. Use template methods for repeated try-catch
  20. Document all exceptions in your application in javadoc

No comments:

Post a Comment