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?
The
usingkeyword is syntactic sugar fortry/finallyand 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.