Correct exception handling
If you look at this post by SantoshZ of the C# team, you'll see code like this:
try
{
conn = new Connection();
conn.Open();
}
catch
{
if (conn != null) conn.Close();
}
Well, this is quite a strange code snippet coming from the
C# team, I must say! It demonstrates bad exception
handling.
Here is what this code should look like in my opinion:
conn.Open();
try
{
...
}
finally
{
conn.Close();
}
Why is that?
- There is no need to call Close() if Open() was not previously executed.
- There is no need to call Close() if Open() failed.
- You probably want "finally" instead of "catch"
Too often do I see code all in a big try...catch block.
BTW, don't forget to use the using statement, which greatly simplifies code in a lot of cases.
