Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are resources disposed even if an exception is thrown in a using block? [duplicate]

Tags:

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?

like image 980
Dot NET Avatar asked Nov 23 '11 12:11

Dot NET


People also ask

What happens if exception thrown in using 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.

Is dispose called when exception is thrown?

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.

Does using block call Dispose C#?

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.


2 Answers

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

like image 92
CodeZombie Avatar answered Sep 23 '22 14:09

CodeZombie


Yes, the resource of the using block will be disposed.

like image 33
Fischermaen Avatar answered Sep 25 '22 14:09

Fischermaen