Best Practices for Using and Writing Exceptions in Java

 

This article lays down some of the best practices which you can use during your design or code reviews. I have learned many of these practices from Effective Java by  Joshua Bloch.

 

Best Practices for Using and Writing Exceptions in Java

  1. Exceptions should be only used for exceptional conditions. It should not be used for control flow like catching an exception and ending a loop.   

    1. APIs must provide alternatives to exceptions to control the flow. For example, if Iterator class in collections does not have a hasNext() method, we would have to use a while(true) loop and then catch NoSuchElementException to exit the loop.

    2. We can have either state testing method (like   hasNext() ) and then call the dependent method (like nextItem()) or return a distinguished value (such as null) when the object is in an inappropriate state.

    3. Though a state testing method is the preferred one, if there is a chance for the state to change between a state testing method call (like hasNext()) and its dependent method (like nextItem()), or if a separate state testing method could duplicate the work of the state dependent method, we can use distinguished return type method.

  2. When using a distinguished return value, we need to make sure that the distinguished value is not a possible correct value that can be returned.

  3. Catching a checked exception and ignoring it is usually a bad idea. Or at the very least, the catch block should have a comment explaining why it is appropriate to ignore.

  4. If there is a chance of recovery, then use checked exception, else use unchecked exception; and if in doubt, it would be better you use unchecked exception. Overuse of checked exception can make an API far less user friendly.

  5. Even though java spec does not require, there is a strong convention that errors are reserved for use by the JVM to indicate failures that make it impossible to continue.

  6. We should not use Throwable instead of checked exceptions as they will simply confuse users.

  7. You should provide methods in your exception classes to get the details of the failure programmatically and should not leave them with no option than to parse the string representation.

  8. Whenever possible use standard exceptions provided by Java or subclass them and add more functionality. This will make the code easier to learn and use. 

  9. Higher layers should catch lower layer exceptions and in their place, throw exceptions that can be explained in terms of the higher level abstraction. This is called exception translation. Exception translation should not be overused.

  10. For better debugging we can do exception chaining by passing the lower level exception (the cause) to higher level exception (using a suitable constructor or Throwable.initCause) and then access it later using an accessor (using Throwable.getCause).

  11. Always declare checked exceptions individually and not a common parent class for all the exceptions; don’t ever declare ‘throws Exception’.

  12. Do not declare unchecked exceptions using throws clause.

  13. Document all checked and unchecked exceptions using the javadoc @throws tag and the conditions under which it is thrown. Even though documenting all of the unchecked exceptions is ideal, it is not always achievable in real world.

  14. Detail message of an exception should capture as much information as possible.

  15. Whenever an exception is thrown from a method, we need to make sure that the current object is in the state prior to execution of that method or at least we should document what state the object will be after that exception is thrown. There are various ways to implement this failure atomicity like making the class immutable, checking parameters for validity and throwing exception before performing the operation, write recovery code to roll back or performing the operation on a temporary copy of the object. If failure atomicity is not practical due to cost and complexity, don’t do it, but document it. Errors are unrecoverable and hence we should not even attempt for failure atomicity for them.

Comments

kmakete's picture

Please explain the above in simplier way.
 
Thank you.

Was it useful?
kmakete's picture

It is talking about Excemptions not,WRITTING TO A FILE.

Was it useful?

Will add a note about writing to file by today/tomorrow and will share the link here. The exception and string notes are for the other two requests.

Was it useful?

Please find few notes I wrote on streams and writing to file.
introduction-to-streams-in-java
read-data-from-keyboard-using-datainputstream-and-write-to-file-using-fileoutputstream
copying-file-contents-using-fileinputstream-and-fileoutputstream
Since I wrote it quickly, I couldn't add much explanations. Please go through and comment on those topics if you have any doubt. 
I will add more notes on reading and writing using Reader and Writer soon.

Was it useful?
kmakete's picture

Thank you.

You voted 'UP'.
Was it useful?

Please refer to the below notes for learning more about String and String Concatenation:

introduction-to-strings-in-java

operator-overloading-in-java

explicit-and-automatic-string-conversion-in-java

If you have more doubts, please ask under the respective topics.

Was it useful?
kmakete's picture

Explain how a CATCH BLOCK can differentiate between different kinds of exceptions.
 
Thank you.

Was it useful?

I have updated the below notes for you. Please refer to them for learning more:

introduction-to-exceptions-in-java

introduction-to-exceptions-hands-on-exercise-and-quiz

If you have further doubts, please ask them below the corresponding articles itself. 

Was it useful?

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)