Exceptions in .Net

I found this snippet on another site, and it looks like it comes from the book I just bought about building frameworks from the guys that worked on the .net framework.

  • DO report execution failures by throwing exceptions.
  • CONSIDER terminating the process by calling System.Environment.FailFast (.NET 2.0) instead of throwing an exception, if your code reaches a situation where you consider it unsafe for further execution.
  • DO NOT use exceptions for the normal flow of control, if possible.
  • CONSIDER the performance implications of throwing exceptions.
  • DO document all exceptions thrown by publicly callable members because of a violation of the member contract and treat them as part of your contract.
  • DO NOT have public members that can either throw or not based on some option such as a bool parameter (.e.g., bool throwOnError)
  • DO NOT have public members that return exceptions as the return value or as an out parameter.
  • CONSIDER using exception builder methods.
  • DO NOT throw exceptions from exception filter blocks
  • AVOID explicitly throwing exceptions from finally blocks.
  • DO throw the most specific (the most derived) exception that makes sense.
  • DO NOT swallow errors by catching nonspecifc exceptions ( e.g., catch (Exception e) { } // swallowed whole!)
  • CONSIDER catching a specific exception when you understand why it was thrown in a given context and you can respond to the failure programmatically.
  • DO Clean up any side effects when throwing an exception. For example, if a Hashtable.Insert method throws an exception, the caller can assume that the specified item was not added to the Hashtable.
  • DO NOT derive all new exceptions directly from the base class SystemException. Inherit from SystemException only when creating new exceptions in System namespaces. Inherit from ApplicationException when creating new exceptions in other namespaces.
  • DO use the predefined exceptions types. Define new exception types only for programmatic scenarios.
  • DO NOT overcatch. Exceptions should often simply be allowed to propagate up the call stack.
  • DO prefer using an empty throw when catching and rethrowing an exception. This is the best way to preserve the exception call stack.
  • AVOID creating custom exception classes when there is already an exception type that’s “good enough”.
  • DO Design classes so that in the normal course of use an exception will never be thrown.
  • DO NOT return Error Codes!
  • Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s