tesicg
tesicg

Reputation: 4053

C#: "using" directive and try/catch block

I know how to use try/catch block in case of database calls and know how to use "using" directive in context of using try/finally construction as well.

But, can I mix them? I mean when I use "using" directive can I use try/catch construction as well because I still need to handle possible errors?

Upvotes: 0

Views: 1874

Answers (4)

Rob Levine
Rob Levine

Reputation: 41298

A using such as:

using (var connection = new SqlConnection())
{
    connection.Open
    // do some stuff with the connection
}

is just a syntactic shortcut for coding something like the following.

SqlConnection connection = null;
try
{
   connection = new SqlConnection();
   connection.Open
   // do some stuff with the connection
}
finally
{
   if (connection != null)
   {
      connection.Dispose()
   }
}

This means, yes, you can mix it with other try..catch, or whatever. It would just be like nesting a try..catch in a try..finally. It is only there as a shortcut to make sure the item you are "using" is disposed of when it goes out of scope. It places no real limitation on what you do inside the scope, including providing your own try..catch exception handling.

Upvotes: 0

Spontifixus
Spontifixus

Reputation: 6660

This one is perfectly valid:

using (var stream = new MemoryStream())
{
    try
    {
        // Do something with the memory stream
    }
    catch(Exception ex)
    {
        // Do something to handle the exception
    }
}

The compiler would translate this into

var stream = new MemoryStream();
try
{
    try
    {
        // Do something with the memory stream
    }
    catch(Exception ex)
    {
        // Do something to handle the exception
    }
}
finally
{
    if (stream != null)
    {
        stream.Dispose();
    }
}

Of course this nesting works the other way round as well (as in nesting a using-block within a try...catch-block.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 837996

You can definitely use both together.

A using block is basically just a bit of syntactic sugar for a try/finally block and you can nest try/finally blocks if you wish.

using (var foo = ...)
{
     // ...
}

Is roughly equivalent to this:

var foo = ...;
try
{
    // ...
}
finally
{
    foo.Dispose();
}

Upvotes: 2

Botz3000
Botz3000

Reputation: 39600

Of course you can do it:

using (var con = new SomeConnection()) {
    try {
        // do some stuff
    }
    catch (SomeException ex) {
        // error handling
    }
}

using is translated by the compiler into a try..finally, so it's not very different from nesting a try..catch inside a try..finally.

Upvotes: 2

Related Questions