Wednesday

Exception Handling - Coding Practices

I have tried to make a short summary from the books, blogs that i readed for Exception Handling. I hope the summary will also be useful for you. If I learn new clues, I'll try to update the post.

1. e.printStackTrace() is a bad practice. It prints to the console. In production environments, console is not watching so you should pass exception to the logger. Also printStackTrace uses a lot of memory because of having whole stack details.

2. All processes in the try catch body should be moved to another function and this another function should throw exceptions and do only processes. It is more easier to understand and trace.

3. In a catch block,  both logging and throwing exception should not be at the same time. Because when the exception is thrown it will be logged again where it will be caught. This causes multiple logging for the same exception. This leads to misleading results, especially in systems where faults are observed.

4. It is better to add parameter values at the end of the exception log. If the generic messages would be at the beginning, tracing the logs will be easier.

5. If you would use try-catch block in your function, then shouldn't be anything before try, after catch/finally block.

6. If in a try catch block all catch blocks do the same process, then combine catch blocks and use only one catch block.

7. Throw the specific checked exceptions instead of generic exceptions.
//FOR EXAMPLE USE:
public void test() throws IOException {

//INSTEAD OF:
public void test() throws Exception {

8. Don't catch Throwable. It includes Errors which means something serious happened on JVM side. So you should let them go VM.

9. You should prefer to use standard Java Exceptions which are more familiar for developers instead of your own exceptions. If you use your own exceptions, then there will be need to be looked another code fragments.

No comments:

Post a Comment