I found this code on the MSDN site here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx:
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
My Question is... the site also notes that .Open()
can throw InvalidOperationExceptions and SqlExceptions, but this example doesn't look like it handles them.
Is this just because they were being brief with the code, or is there a reason they're not worth handling here? are they possibly handld by the using construct in some way?
Is this just because they were being brief with the code, or is there a reason they're not worth handling here? are they possibly handld by the using construct in some way?
The using
keyword is syntactic sugar for try/finally
and even though possible exceptions won't be handled on the code you referenced, the SQL Connection will be disposed properly. They are probably not handling the possible exceptions explicitly because many prefer to let the exception bubble up to the the highest layer and handle the exception there.
MSDN examples are written to provide an easy to read example, not to teach best practices. That's one reason why people should not copy/paste code without understanding it.
Per MSDN
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called.
It will close the open connection (through the use of finally). It will not catch the exception being thrown. It does so by wrapping the enclosed statement in a try/finally. There is no catch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With