If I have a connection in a using statement, will the connection be closed if an exception occurs in the using statement?

StackOverflow https://stackoverflow.com/questions/23231504

Question

The following code doesn't have any sort of error handling.

I'm curious though. As it sits, will the connection that is created in the using statement be closed when the exception is thrown? Or will the connection remain open because it was never explicitly closed?

public override string ResetToDefault() {
    string result;
    using (var cn = HostFacade.GetDbConnection())
    {
        cn.Open();
        DbProvider.Transaction = cn.BeginTransaction();

        // Do something here that throws an unhandled exception.

        DbProvider.Transaction.Commit();
        cn.Close();
    }
    return result;
}

Edit: The connection being returned by HostFacade.GetDbConnection is an IDbConnection. It's safe here to assume it's being implemented as a SqlConnection object.

Was it helpful?

Solution

Yes, because a using statement is expanded by the compiler to be a try...finally block. Your code is the same as this:

SqlConnection cn = null;

try {
    cn = HostFacade.GetDbConnection();
    cn.Open();
    // .. rest of the code here
}
finally {
    if (cn != null)
        cn.Dispose();
}

The Dispose call will close the connection.

The CLR guarantees that a finally block will execute.. except in very specific scenarios (such as a call to FailFast IIRC).

OTHER TIPS

It depends on the implementation of Dispose() by the author of the specific library you are running.

Libraries built into the .NET Framework (like your example) will undoubtedly clean up the resources accessed, like the SqlConnection, but you should verify with documentation first, before assuming anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top