Possible Duplicate:
Does Dispose method still get called when Exception is thrown inside of Using statment?
I've got a number of using
blocks, when accessing a database. I was wondering - if an exception had to be thrown within the using block, would the necessary resources still be disposed, even though the end of the block is not reached? Or would I need to close them myself manually in the catch
block?
If any code throws an exception within that try block, the exception will be handled by the corresponding catch. catch – When an exception occurs, the Catch block of code is executed.
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.
The resources defined with the using
statement were disposed, this is the main reason what using
is good for.
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.
http://msdn.microsoft.com/en-us/library/yh598w02%28v=VS.100%29.aspx
Yes, the resource of the using block will be disposed.
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