Please enable JavaScript to view the comments powered by Disqus.

Best Practices for Exception Handling

Exception handling is an important part of developing robust application.

It’s a process to response to a erroneous situation like invalid input value, not found resource,…

Here are some best practices  for Exception Handling that I collected from my working experience and the Internet.

1. Don't overuse Exceptions

Remember that Exception is costly and can slow down your code!

Try to minimize unnecessary exceptions. Don’t just throw and catch exceptions any where you like in your code.

Only use exception in “exceptional” conditions, do not use it to manage your business logic, try if-else statement instead.

2. Avoid empty catch block

Using empty catch block will not only hide your app’s errors but also leave your objects in unused and corrupt state.

Ignore a error can save you at this time but will kill you at mantainance :))

If you use exception, remember to log all error details:

  • with unique name/ message (This will help you identify exception location easier)
  • with meaningful message (Ex. Use "Illegal value for ${argument}: ${value}" instead of "Incorrect argument for method" )
  • with proper exception type:
    • Fatal: can cause system crash
    • Error: lack of requirement
    • Warn: not an error but can be in the future
    • Infor: information for user
    • Debug: information for developer

3. Close or release resources in finally block

This is a must-know best practice - Always clean up all resources in finally block! :)

4. Catch specific exceptions instead of the top Exception class

This will increase the performance, help your code more understandable and more specific.

5. Try not to re-throw the exception

The reason is costly price!

But if you mus re-throw the exception, re-throw the same exception object instead of creating  a new one!

6. Use exception outside the loop

Exception handling inside a loop is not recommended for most cases.

Surround the loop with exception block instead.

P/S: A co-worker share this to me :”>

7. Use your own exception hierarchy

By extending current Exception class (e.g. UserException, SystemException and their sub types), you can define your own exception hierarchy and use them.

By doing this you can specialize your exceptions and define a reusable module/layer of exceptions.

 

That’s all the best practices for exception handling in this post!

If you think this is not enough, please comment below :)