sharp bites

standing on the shoulders of giants

Exce(r)ptions

Just a few notes on exceptions to remind, from Karl Seguin.
Handling exceptions
1 - Only handle exceptions that you can actually do something about, and
2 - You can’t do anything about the vast majority of exceptions

Logging
You should log every exception. Ideally you’ll centralize your logging - an HttpModule’s OnError event is your best choice for an ASP.NET application or web service.

Handling database access (and its possible exceptions):
using (SqlConnection connection = new SqlConnection(FROM_CONFIGURATION))
using (SqlCommand command = new SqlCommand("SomeSQL", connection))
{
connection.Open();
command.ExecuteNonQuery();
}


throw vs. throw ex
On occasion you’ll need to rethrow an exception because, while you can’t handle the exception, you still need to execute some code when an exception occurs. In this case you should use throw to preserve the full exception stack. Contrary, if you find yourself in a situation where you think you want to rethrow an exception with your handler as the source, a better approach is to use a nested exception:
catch (HibernateException ex)
{
if (transaction != null) { transaction.Rollback(); }
throw new Exception("Email already in use", ex);
}


When to throw
A method should throw when it wasn’t able to do what it was suppossed to do.

If you want a more in-depth explanation on the subject, I recommend you go and read the article

Comments