-
// 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.