CSC510236. Do not suppress general exceptions.

Description

The exception itself should not be ignored because it can be affected to regular program flow. There are three exception types (logical groups):
  1. Usage exceptions. Means you try to use method with wrong parameters. Validate method parameter at first and throw such exception BEFORE main code. Never catch or handle it.
  2. System exceptions. Raised when something abnormal happened inside the method main code and not related from caller. Generally it is required to re-throw exception up. Catch it only:
    1. it is possible to compensate results, make a workaround actions;
    2. on the application top level to avoid user from stress from exception technical detals;
    3. to wrap original exception into custom exception type.
  3. Application exceptions like NullReferenceException, InvalidOperation etc. These are about logic problem in code. You can handle its with the same reasons as for system exceptions.

public void CallerMethod()
{
  try  {
    CalledMethod("Test")
  }
 // DO NOT CATCH USAGE EXCEPTION
 catch(ArgumentNotSpecifiedException ex) {
      // special handling for ArgumentNotSpecifiedException 
  }   
 catch(Exception ex) {
      // log it
      throw new WrappedException("Method XXX call  error occurred", e); // wrapped & chained exceptions.
  }   
  finally {
  // normal clean goes here (like closing open files).
  }
}

public void CalledMethod(string p1)
{
  // Validate parameter and throw "usage exception"
  if (String.IsNullOrEmpty(p1))
    throw new ArgumentNotSpecifiedException("Parameter p1 must be specified")

   // Here we save data to the storage and the "system exception" could be raised
   try {
     DAL.Save(p1);
   }
   catch (SqlException e) {
    if (e.ErrorCode != NO_ROW_ERROR) { 
      // filter out NoDataFound.
      // do special cleanup, like maybe closing the "dirty" database connection.
      // throw e; <- DO NOT DO IT. This destroys the strack trace information!
      throw; // this preserves the stack trace
    }
  } 

}

In case of logging handle exception with re-throw. It will allow to take a decision on the upper level.

Resolution

  1. If method has a side-effect it is strongly recommended to avoid ANY exception suppressions, not only specific type.
  2. Specify exception type in the catch clause. Mostly it could be SPException.
  3. Rethrow exception in catch(Exception) block using throw or catch specific exception.

Links

Design Guidelines for Exceptions
The Pragmatic Programmer
Clean Code: A Handbook of Agile Software Craftsmanship
SPException class

Last edited May 7, 2014 at 11:42 AM by dvd73, version 16

Comments

No comments yet.