views:

116

answers:

4

Bit by bit I am collecting knowledge of C#.
What Ill like to learn is Good design of Exception handlig ?
Form where I should start ? Any Blog , Book or similar ?
Is there at all good practice for handling exception or that depends on programmers intuition and state of art or experience whatever?
I come to this point for asking this kind of help after I lost two days looking at code: I handled exception for database retrieval, But did not handle well situation when returned parameters of SQL stored procedure contain null type, and things like that

A: 

I think you need to be more specific in your question. For catching an exception from SQL, you'd wrap your code like this:

try 
{

   using (var conn = new SqlConnection())
   {
       // Config your SQL connection, query etc.
   }
}
catch (SqlException sqlEx) 
{
   // Handle SqlException exception here. 
}
catch (Exception ex) 
{
   // Catch all other exceptions here.
}

What do you mean by "[it] did not handle well in situations when returned parameters of SQL stored procedure contain null type, and things like that"?

TheCloudlessSky
+3  A: 

The vast majority of thrown exceptions (particularly usage exceptions like NullReferenceException or ArgumentException) indicate bugs and really shouldn't be caught or should only be caught at a very high level to provide logging and graceful failure presentation to the user.

A few general ideas that have been helpful for me:

  1. Watch for Exceptions at boundaries of interaction with unreliable systems, such as users (users are notoriously unpredictable), file systems, database systems, network I/O, remoting, etc. If you're not sure where these boundaries are, consider changing the structure of your code so that the reliability/trust boundaries are clear.

  2. Only catch the types of Exceptions at those boundaries that you know about. You'll have to determine on a case by case basis how you want to handle these cases. For instance, it's always possible that someone can pull the network cable and your network I/O will begin to fail with SocketException; it's up to you to decide how you'll handle this.

  3. It's better to validate your inputs before-hand so that you don't trigger Exceptions, wherever possible. This is particularly important at the level of user interaction, where you should be exceedingly suspicious of every single thing the user gives you. It helps to have a good usage tester to identify these things. There's a guy in my office who does evil things like enter all spaces in text boxes, enter 100s of characters, click furiously on numerous buttons, etc.

Dan Bryant
+5  A: 

Eric Lippert has an excellent article on the different types of exceptions you may encounter and how you should be handling them.

The four classes he uses are fatal, vexing, boneheaded and exogenous.

http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx

Alex Humphrey