In C#, if an exception occurs inside a "using" block, does the Dispose method get called?
The exception is thrown, because there is no catch statement in the compiled code. If you handle the exception within the using block, your object will still be disposed in the compiler-generated finally block.
The answer is no. Dispose() does not get called in the attached code. Further more the exception that is thrown is not handled and the program blows up.
What is the use of using statement in C# ? Placing your code inside a using block ensures that it calls Dispose() method after the using-block is over, even if the code throws an exception.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With