Disposable, Use and Try / Catch Blocks

Today, when there is a mental block, you need a hand to verify that my logic is not fubar'ed.

Traditionally, I would make an i / o file similar to this:

FileStream fs = null; // So it 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, it is not very elegant.

Ideally, I would like to use the using block to get rid of the filter when done, however I'm not sure about the synergy between use and try / catch.

Here is how I would like to implement the above:

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

However, I am concerned that a premature exit (through an exception) from within the used block may not allow the executing block to complete execution and clear it. Am I just paranoid, or will it work the way I intend it?

+7
c # using-statement
source share
6 answers

You are just paranoid and it will work the way you intend it :)

The using statement is equivalent to a try / finally block, whether inside try / catch or not.

So your code is like:

 try { FileStream fs = null; try { fs = File.Open("Foo.txt", FileMode.Open); // Do stuff } finally { if (fs != null) { fs.Dispose(); } } } catch(Exception) { /// Handle Stuff } 
+17
source share

Do not worry, it will clear as expected and become cleaner than your original.

Actually, it is much more common to use try / finally aka using statement in your business logic and try / catch in a top-level handler at the user interface level or at the physical layer boundary. Something like:

 try { DoStuffWithFile("foo.txt"); } catch(Exception ex) { ... } 

and

 public void DoStuffWithFile(string fileName) { using(FileStream fs = File.Open(fileName,...)) { // Do Stuff } } 
0
source share

This will work - internally, the using statement compiles the same way as the try-finally block

0
source share
  try { FileStream fs = null; try { fs = File.Open("Foo.txt", FileMode.Open); } finally { fs.Dispose(); } } catch(Exception) { /// Handle Stuff } 

the second part of the code will be translated into this

0
source share

The use block will work just like you translate the use block, really simple

 try { FileStream fs = null; try { fs = File.Open("Foo.txt", FileMode.Open)) //Do Stuff } finally { if(fs != null) fs.Dispose(); } } catch(Exception) { /// Handle Stuff } 
0
source share

You do not need to try..finally if you have using() . They perform the same operation.

If you are not sure, specify a Reflector in your assembly and compare the generated code.

0
source share

All Articles