Saturday, September 09, 2006

 

.NET Exception Handling Guidelines: Throwing Exceptions (part 2)

Exceptions are aptly named! Throw them in exceptional circumstances. A public method represents a contract with consumers. A method should raise an exception whenever it cannot successfully complete the task that its name implies it was designed to accomplish.

  • Report execution failures by throwing exceptions; do NOT return error codes.
  • Do NOT use exceptions for the normal flow of execution, if at all possible.

Don’t do this!:


foreach (Item i in someList)

{

try

{

someOtherList.Add(i);

}

catch

{

// swallow failures, where i already exists in someOtherList...

}

}



  • Create exceptions sparingly. Wherever possible, throw existing exceptions (from the System namespaces), rather than creating new ones.
  • Create and throw custom exceptions in situations where an error condition can be handled in a more specific way than existing exceptions.
  • Always throw the most specific exception that is applicable.
  • When throwing an exception, provide a descriptive and useful message, explaining the cause of the exception. Since exception messages are only relevant when an exception is unhandled, the message text should be aimed at helping developers fix the bug.
  • Check for bad arguments supplied to methods and throw ArgumentException, ArgumentNullException and ArgumentOutOfRangeException exceptions where appropriate. Set the ParamName property when throwing one of these. Code should almost never need to catch any of the Argument exceptions.
  • Do NOT throw System.Exception or System.SystemException
  • Do NOT throw OR derive from System.ApplicationException
  • Do NOT throw CLR exceptions.

part 1, part 3 and part 4 are here



    

Powered by Blogger