Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlConnection in C# - Safe programming practice

Tags:

c#

.net

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?

like image 209
John Humphreys Avatar asked Apr 30 '12 14:04

John Humphreys


Video Answer


2 Answers

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.

like image 133
Icarus Avatar answered Oct 10 '22 05:10

Icarus


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.

like image 34
P.Brian.Mackey Avatar answered Oct 10 '22 05:10

P.Brian.Mackey