7

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?

1
  • .Open() will throw an exception if the connectionString is invalid, the SqlConnection object is null or empty or if no connection could be made to the server (or local database). In that case, they assume that the connection string is valid and the using statement assure that connection isn't null. Commented Apr 30, 2012 at 14:21

7 Answers 7

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks everyone, that clears it up alot. I'm coming from a C++ backgorund, so I like to double check on some of these things to make sure they're not doing more than I think they are :)
4

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.

1 Comment

Agreed. Part of the problem with doing best practices in example code is that it's much harder for newbies to figure out what's going on.
3

It depends if there's anything you can "do" upon trapping these exceptions.

If not - its generally considered best practice to let exceptions bubble up the stack, until they reach a point where they can be handled in a meaningful way (which may just be logging a 500 error, in the case of a web-app)

Comments

2

These cases are being handled.

The using statement gets translated to a proper dispose pattern that also handles disposal in cases of exceptions.

In this case, even if an exception is thrown, the connection will be disposed of.

The exception itself will bubble up.

See using Statement on MSDN for details.

3 Comments

can you explain this a little more for me or give a link I can read?
They are not being handled.
@KendallFrey - The cases for disposal will be handled regardless of exceptions. Rephrased answer.
1
using (SqlConnection connection = new SqlConnection(connectionString))
    {

    }

is equivalent to

try
{

    SqlConnection connection = new SqlConnection(connectionString)
}
finally
{
   connection.Dispose();
}

"using" is just to make sure that the dispose() method on the object gets called (in this case to make sure the connection gets returned to the connection pool). "using" was never meant to replace catch.

On the projects I have worked on, typically we have a lot of try finally. Catch is used only at the highest level to log it. One reason catch should not be used to re throw errors (as opposed to logging it) is that catch is very resource intensive.

Comments

0

This sample is confusing, while technically correct. In a real world application this sample "as is" has no value.
They don't even return the SqlConnection to a calling code.
So "they were being brief with the code" as you said.

In a real world scenario you could have a method like this

private static SqlConnection OpenSqlConnection(string connectionString) 
{ 
    SqlConnection connection = new SqlConnection(connectionString)
    connection.Open(); 
    return connection;    
} 

and then use it in your code (albeit there is no much to gain)

using(SqlConnection cnn = OpenSqlConnection(connectionString))
{
    // Do your work here
    ....
}

of course the using statement hides all the works to catch exceptions and closing/disposing everything so, while, technically speaking the exceptions are handled, in reality you don't get any clues if something fails.

4 Comments

What do you mean, "you don't get any clues"? You get an exception, which is a very big "clue".
@JohnSaunders I was thinking about this. If using is like a try/finally block, what happen if inside the using block we get an exception? Will it bubbles up outside the block and we can take notice or will it be 'eaten' by the finally masked by the closing brace?
Just found this, reading now to understand better
Using is like Try/Finally, not like Try/Catch. It does not eat exceptions since it doesn't catch them.
0

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.Try/catch is expensive. try/catch can affect compiler optimization and what programmer would use try/catch over doing something as simple as checking for null. It is just bad practice. Catching an exception will always be slower than doing a simple check. I'm not saying doing use them but don't use them in place of defensive programming.

Also, looking at the code the "open" command would be called only if there is a valid connection..so no worries....

"Using" is same as putting the object inside a try block and then calling Dispose in a finally block.

If you still need to handle any specific exceptions, include the try..catch..

1 Comment

-1: using does nothing to prevent the application from crashing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.