Monday, April 18, 2011

.NET exceptions, error handling for the exceptional case

The tip of the day consists of, in making sure to use a try/catch block to trap individual exception types such as SqlException which is specific whereas Exception being more general.

For instance, imagine you are connecting to a database, it's quite common to experience a connection failure that you might not expect. So it makes sense to try to handle any unexpected connection failures.

First, try and discover the SqlConnection members class on msdn and drill down to the SqlConnection.Open method, there's a section including the exceptions that the open method may throw and we find two :

InvalidOperationException and SqlException with the specifics on what the conditions are when these exceptions are thrown.

Similarly, we can write code likewise :


 //connect to db and do something useful
catch(InvalidOperationException invalidException)
 // specific exception
 // usually occurs when trying to open a conenction
catch (SqlException sqlexception)
 // specific exception
 // will occur when opening a connection
catch (Exception exception)
   // lastly the general exceptional case will kick in
   // could be anything that the first two exceptional cases didn't catch.

Note how Exception ( the mother of all exceptions) is handled last and instead we branch out by starting with more specific exceptions, InvalidOperationException and SqlException. This allows us to catch more specific exceptions and then move on to the more general exceptions. This is a good practice.

Lastly, when logging your exceptions, use the default implementation of ToString of the exception thrown to obtain the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace with line number etc.

Final notes:
If an exception can be handled programmatically without resorting to try/catch then investigate that route first. Handle the exceptions that are relevant to your code, throw back everything else. Read Best Practices for Handling Exceptions

References :

kick it on
Shout it

No comments:

Post a Comment