Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using statement with try catch. What happens to instance from using statement?

If I have a using block surrounding a try catch statement what will happen to the object inside that using statement should the catch fire an exception? Consider the following code:

using (IDatabaseConnectivityObject databaseConnectivityObject = new DbProviderFactoryConnectionBasicResponse())
{
    try
    {
        Foo();
    }
    catch (ArgumentNullException e)
    {
        throw;
    }
}

If we assume Foo() fails and the exception is fired and effectively breaks the program will databaseConnectivityObject be disposed? The reason this is important is that the object has a database connection associated with it.

like image 850
CSharpened Avatar asked Sep 03 '12 10:09

CSharpened


2 Answers

You can think of using as a short-hand for try-finally. Hence your code is equivalent to:

IDatabaseConnectivityObject databaseConnectivityObject = new DbProviderFactoryConnectionBasicResponse();
try
{
    try
    {
        Foo();
    }
    catch(ArgumentNullException e)
    {
        throw;
    }
}
finally
{
  if(databaseConnectivityObject != null)//this test is often optimised away
    databaseConnectivityObject.Dispose()
}

Looked at this way, you can see that the Dispose() will indeed be called if the exception throws, because the try-finally is outside of the try-catch.

This is precisely why we use using.

like image 138
Jon Hanna Avatar answered Nov 07 '22 03:11

Jon Hanna


we assume Foo() fails and the exception is fired and effectively breaks the program will databaseConnectivityObject be disposed?

Yes it will be. using internally uses try-finally, (using only works for those which implements IDisposable)

From MSDN- using statement

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

like image 23
Habib Avatar answered Nov 07 '22 04:11

Habib