Rules to Better .NET Projects

Microsoft Gold Partner Logo
Search Go Search
Rule #22
Do you Open your Connection in a Try Block?
  v3.0 Posted at 20/10/2010 7:56 PM by system

In situations where you must explicitly open a connection (e.g. when using data readers), you always:

  • open your Connection in a Try Block and
  • close it in a Finally statement (So when an Exception is thrown your Connection can be properly closed)

 

                        // C# 
try
{
    cnn.Open();
    cmd.ExecuteReader();
}
catch (SQLException ex)
{
    MessageBox.Show(ex.Message);
    cnn.Close();
}

'VB.NET
Try
    cnn.Open()
    cmd.ExecuteReader()
Catch (ex as SQLException)
    MessageBox.Show(ex.Message)
    cnn.Close()
End Try
Bad code - Connection is not closed in the finally.
                        // C#
try
{
    cnn.Open();
    cmd.ExecuteReader();
}
catch (SQLException ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    cnn.Close();
}
' VB.NET
Try
    cnn.Open()
    cmd.ExecuteReader()
Catch (ex as SQLException)
    MessageBox.Show(ex.Message)
Finally
    cnn.Close()
End Try
Good code - The cnn.open is in a Try and the cnn.Close is in a finally
Note:Do not use the 'using' keyword in C#. The using keyword is used to declare a scope out of which the connection will be disposed. For the sake of consistancy, we like out VB.NET and C# projects to be as similar as possible. For both languages you should use a Try..Catch..Finally block.
 

Loading
Do you like this rule?
Loading
Do you follow this rule?
Loading

......