InterviewSolution
| 1. |
Best Practices of Exception Handling in Java |
|
Answer» Exception handling is the process that deals with the occurrence of exceptions during computation. Some of the best practices of exception handling in Java are given as follows:
There are many resources that are used in a TRY block that need to be closed afterwards. HOWEVER, these resources should not be closed in the end of the try block as it may never be reached if any exception is thrown. So, all the cleanup code should be in the finally block for better results.
The superclass of all the exceptions and errors is throwable. It should never be used in a catch clause as it will catch all exceptions and errors, some of which may be outside the control of the APPLICATION and so unable to be handled.
Descriptive messages should be provided with exceptions that help to understand why the exception was reported to the monitoring tool or the log file. The descriptive messages should be precise and describe the exceptional event problem as clearly as possible.
All the exceptions that are specified in the method signature should also be documented in the Javadoc. This is quite useful as it provides the caller with more information that helps to handle or avoid the exception as required.
Never ignore an exception under the assumption that it will never occur. This is faulty as the code may change in unforeseen ways in the future and the exceptions thought not required as a particular event would never occur might just occur.
The most specific exception class should be catched first and the less specific catch blocks should be provided later as the first catch block that matches an exception gets executed. So, if the less specific exception catch block is given first, then the control may never REACH the more specific exception catch block.
It is better to have as specific exceptions as possible as they make the API easier to understand. This means that the class which is the best fit for the exceptional event should be used and unspecified exceptions should be avoided.
Do not log and rethrow exceptions as it leads to multiple error messages for the same exception. These additional error messages are quite useless as they do not provide any extra information. If any additional information is required, the exception should be caught and wrapped in a custom one. |
|