In C#, if an exception occurs inside a "using" block, does the Dispose method get called?
Asked
Active
Viewed 9,192 times
8
-
2YES................................. – L.B Feb 03 '14 at 17:24
-
http://stackoverflow.com/a/10984354/1344 – Brian Warshaw Feb 03 '14 at 17:29
-
2What does google return when you type your keywords `c# using dispose exception` ? – I4V Feb 03 '14 at 17:32
-
@Brij No, **first result** is your answer – L.B Feb 03 '14 at 17:40
-
1@Brij You do realize that even though they are “StackOverflow questions” they are usually answered? – poke Feb 03 '14 at 17:46
-
@poke, yes the questions in StackOverflow are answered. – Brij Feb 03 '14 at 17:57
1 Answers
23
Yes it will get called.
using
translates into try-finally
block, so even in case of recoverable exception Dispose
gets called.
See: using statement C#
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.
Consider SqlConnection
which implements IDisposable
interface, so the following:
using (SqlConnection conn = new SqlConnection("connectionstring"))
{
//some work
}
Would get translated into
{
SqlConnection conn = new SqlConnection("connectionstring");
try
{
//somework
}
finally
{
if (conn != null)
((IDisposable)conn).Dispose(); //conn.Dispose();
}
}

Habib
- 219,104
- 29
- 407
- 436