28

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?

Community
  • 1
  • 1
Dot NET
  • 4,891
  • 13
  • 55
  • 98

4 Answers4

44

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

CodeZombie
  • 5,367
  • 3
  • 30
  • 37
4

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

Fischermaen
  • 12,238
  • 2
  • 39
  • 56
1

You wouldn't. Actually the using block is the same if you use try{}catch{}finally{} construction with Dispose method call in the finally block. So it will be called anyway.

Yuriy Rozhovetskiy
  • 22,270
  • 4
  • 37
  • 68
1

Yes, the element will be disposed of, as the call is part of the finally block of the try into which the using translates.

From 8.13 of the C# specification:

A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.

So you won't need to dispose of it manually, and I'm unsure of where your own catch block would be in this case anyway.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129