Disposables, Using & Try/Catch Blocks

Posted by Aren B on Stack Overflow See other posts from Stack Overflow or by Aren B
Published on 2010-04-28T18:12:48Z Indexed on 2010/04/28 18:17 UTC
Read the original article Hit count: 563

Filed under:
|
|

Having a mental block today, need a hand verifying my logic isn't fubar'ed.

Traditionally I would do file i/o similar to this:

FileStream fs = null; // So it's visible in the finally block
try
{
   fs = File.Open("Foo.txt", FileMode.Open);

   /// Do Stuff
}
catch(IOException)
{
   /// Handle Stuff
}
finally
{
   if (fs != null)
      fs.Close();
}

However, this isn't very elegant.

Ideally I'd like to use the using block to dispose of the filestream when I'm done, however I am unsure about the synergy between using and try/catch.

This is how i'd like to implement the above:

try
{
   using(FileStream fs = File.Open("Foo.txt", FileMode.Open))
   {
      /// Do Stuff
   }
}
catch(Exception)
{
   /// Handle Stuff
}

However, I'm worried that a premature exit (via thrown exception) from within the using block may not allow the using block to complete execution and clean up it's object. Am I just paranoid, or will this actually work the way I intend it to?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET