Monday, January 13, 2014

On Exception Handling

Exception Handling:

A) Never swallow the exceptions in catch block: Catching exceptions and swallowing is very danger than not catching them. This counter impacts the quality. If you don't want to process the exceptions then don't unnecessarily catch it. There are few very rare cases to swallow an error but it should be justified.

B) There can be 5 reasons to catch exceptions: The following can be reasons for wrapping a code fragment in a try...catch block:

  1. You want to recover from it by retrying the operation 
      for example a database server connection. Want to connect to alternate server.
  2. You want to add some extra information in to the exception you have catched and re-throw
  3. You want to cleanup some resources in finally block
  4. You want to ask the user what to do by providing some possible options.
  5. You want to log the full error stack and display a fancy message to the user

C) Exceptions are expensive in terms of performance. Don't drive the whole business logic with just exceptions. Where possible pre-check the possible error conditions and throw the exceptions.

D) Don't use error codes to like 1001, 1, 2 etc. to return an error states. User's of those methods can fail to check for them. For example there can be a possible null or divide by zero then check for them and throw the exception.

E) Create your own exceptions derived from framework's Exception base class and use them to drive and enforce the business logic, rules and policies.

F) Always wrap the higher level (top most where the code execution entry points) methods in a try...catch block. For example: all event handlers in a Win, WPF, Web Form application. The service entry points for Web service, Web/REST API services. This is means catch only the boundaries.

I'll do more posts with thorough and detailed examples.

No comments:

Post a Comment