Does Dispose still get called when exception is thrown inside of a using statement?
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?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:
- Intercepting an exception inside IDisposable.Dispose
- What is the proper way to ensure a SQL connection is closed when an exception is thrown?
- C# "Using" Syntax
- C# USING keyword - when and when not to use it?
- 'using' statement vs 'try finally'
- What is the C# Using block and why should I use it?
- Disposable Using Pattern
- Does End Using close an open SQL Connection
This is how reflector decodes the IL generated by your code:
private static void Main(string[] args) { SqlConnection conn = new SqlConnection("..."); try { conn.Open(); DoStuff(); } finally { if (conn != null) { conn.Dispose(); } } }
So the answer is yes, it will close the connection if
DoStuff()throws an exception.