Sunday, September 10, 2006

 

.NET Exception Handling Guidelines: Catching Exceptions (part 4)

  • Unless you are writing framework code, do not consume non-specific errors by catching System.Exception or System.SystemException.
  • There are occasional circumstances when swallowing errors in applications are justified, but these are few and far between.
  • Do NOT over catch. Over-catching can hide bugs. Let exceptions propagate up the call stack.
  • Catch specific exceptions only when you know you can recover from them. Do NOT catch exceptions you can do nothing about.
  • If you can avoid throwing an exception, by using a TryParse, Exists or some other method, do so.
  • Use try-finally rather than try-catch for cleanup code.
  • For objects that implement IDisposable consider the using statement:
using (SqlConnection connection = new SqlConnection(connectionString))

{

}


  • Try to avoid catching and rethrowing: it can decrease the effectiveness of debugging.
  • If you do catch and rethrow an exception, use an empty throw rather than throw ex, otherwise you will lose the original exception’s call stack:

try

{

    //...code that might throw here...

}

catch (CustomException ex)

{

    // perform some specific handling here...

    throw; //rethrow the original exception

}


The links to the previous posts on this topic are here: part 1, part 2, part 3.



    

Powered by Blogger