Catching Exception inside Using statement

RG-3 picture RG-3 · Apr 17, 2012 · Viewed 27.6k times · Source

I know that Using statement disposes out the object that is being created. Like if I wanted to do something like this:

    Using(SqlConnection conn = new SqlConnection(connString))
    {
      //some code
      //How to show the users if conn is not opened up or generated some kind of error?
    }

How to show the users if conn is not opened up or generated some kind of error?

Answer

marc_s picture marc_s · Apr 17, 2012

There's nothing special about code written inside a using block - just use a try.catch to handle exceptions:

using(SqlConnection conn = new SqlConnection(connString))
{
    try
    {
        conn.Open();
        // do more stuff here......

    }
    catch(SqlException sqlEx)
    {
       // log error and possibly show to user in a MessageBox or something else
    }
}

The using(...) { ... } block itself is designed only to ensure that the resource / object it "encapsulates" is properly disposed of when it's no longer needed. There's is nothing you can do with the using statement itself to make it handle errors.

So if you expect that just creating the object could fail, then you'd have to put the entire using block inside the try ... catch block , or fall back to a try ... catch ... finally block and ensure proper disposal yourself (as Adam suggested in his answer).