Posts Tagged ‘Best Practices’

Best Practices for Handling Exceptions

A well-designed set of error handling code blocks can make a program more robust and less prone to crashing because the application handles such errors. The following list contains suggestions on best practices for handling exceptions:
  1. Know when to set up a try/catch block. For example, you can programmatically check for a condition that is likely to occur without using exception handling. In other situations, using exception handling to catch an error condition is appropriate.
  2. Use try/finally blocks around code that can potentially generate an exception and centralize your catch statements in one location. In this way, the try statement generates the exception, the finally statement closes or deallocates resources, and the catch statement handles the exception from a central location.
  3. Always order exceptions in catch blocks from the most specific to the least specific. This technique handles the specific exception before it is passed to a more general catch block.
  4. End exception class names with the word “Exception”. For example:
    public class MyFileNotFoundException : Exception {
  5. In C#, use at least the three common constructors when creating your own exception classes. For an example, see How to: Create User-Defined Exceptions.
  6. In most cases, use the predefined exceptions types. Define new exception types only for programmatic scenarios. Introduce a new exception class to enable a programmer to take a different action in code based on the exception class.
  7. For most applications, derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value.
  8. Include a localized description string in every exception. When the user sees an error message, it is derived from the description string of the exception that was thrown, rather than from the exception class.
  9. Use grammatically correct error messages, including ending punctuation. Each sentence in a description string of an exception should end in a period.
  10. Provide Exception properties for programmatic access. Include extra information in an exception (in addition to the description string) only when there is a programmatic scenario where the additional information is useful.
  11. Return null for extremely common error cases. For example, Open returns null if the file is not found, but throws an exception if the file is locked.
  12. Design classes so that an exception is never thrown in normal use. For example, a FileStream class exposes another way of determining whether the end of the file has been reached. This avoids the exception that is thrown if you read past the end of the file. The following example shows how to read to the end of the file.class FileRead {
    public void Open(FileStream fileToRead)
    // This if statement is optional
    // as it is very unlikely that
    // the stream would ever be null.
    if (fileToRead == null)
    throw new System.ArgumentNullException();

    int b;

    // Set the stream position to the beginning of the file.
    fileToRead.Seek(0, SeekOrigin.Begin);

    // Read each byte to the end of the file.
    for (int i = 0; i < fileToRead.Length; i++)
    b = fileToRead.ReadByte();
    // Or do something else with the byte.

  13. Throw an InvalidOperationException if a property set or method call is not appropriate given the object’s current state.
  14. Throw an ArgumentException or a class derived from ArgumentException if invalid parameters are passed.
  15. The stack trace begins at the statement where the exception is thrown and ends at the catch statement that catches the exception. Be aware of this fact when deciding where to place a throw statement.
  16. Use exception builder methods. It is common for a class to throw the same exception from different places in its implementation. To avoid excessive code, use helper methods that create the exception and return it.
Source: MSDN, CodeProject
~ Gangadhar Kotu