Does Dispose still get called when exception is thrown inside of a using statement?

Brian Kim picture Brian Kim · Feb 5, 2009 · Viewed 28.7k times · Source

In the example below, is the connection going to close and disposed when an exception is thrown if it is within a using statement?

using (var conn = new SqlConnection("..."))
{
    conn.Open();
    // stuff happens here and exception is thrown...
}

I know this code below will make sure that it does, but I'm curious how using statement does it.

var conn;
try
{
    conn = new SqlConnection("...");
    conn.Open();
    // stuff happens here and exception is thrown...
}
// catch it or let it bubble up
finally
{
    conn.Dispose();
}

Related:

What is the proper way to ensure a SQL connection is closed when an exception is thrown?

Answer

Jeff Yates picture Jeff Yates · Feb 5, 2009

Yes, using wraps your code in a try/finally block where the finally portion will call Dispose() if it exists. It won't, however, call Close() directly as it only checks for the IDisposable interface being implemented and hence the Dispose() method.

See also: