2010-04-28 55 views
7

今天有一個心理障礙,需要一個手來驗證我的邏輯沒有被fubar化。一次性使用&使用&try/catch塊

傳統,我會做文件I/O與此類似:

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(); 
} 

然而,這是不是很優雅。

理想情況下,我想在完成後使用using塊來處理文件流,但我不確定使用和try/catch之間的協同作用。

這是怎麼了,我想實現以上:

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

但是,我擔心在使用塊中的過早退出(拋出通過除外)可能不允許使用塊完成執行並清理它的對象。我只是偏執狂,還是會按照我的意圖行事?

回答

17

你只是被偏執它一定會給你想要的方式來:)

using語句相當於try/finally塊,無論是在try/catch或不內。

所以,你的代碼是類似於:

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

別擔心,它會清除如預期,並且比原來的更乾淨。

事實上,在您的業務邏輯中嘗試/最終再次使用語句以及在UI層或物理層邊界的頂級處理程序中嘗試/捕獲更爲常見。喜歡的東西:

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

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

這將工作 - 內部using語句編譯方法一樣一個try-finally塊

0
try 
    { 
     FileStream fs = null; 
     try 
     { 
      fs = File.Open("Foo.txt", FileMode.Open); 

     } 
     finally 
     { 
      fs.Dispose(); 
     } 
    } 
    catch(Exception) 
    { 
     /// Handle Stuff 
    } 

代碼的第二件被翻譯成這個

0

使用塊將工作完全符合你所要翻譯的使用塊是真實的LY只是

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

你不需要try..finally如果你有一個using()。他們執行相同的操作。

如果您不確定,請在您的程序集中指向Reflector並比較生成的代碼。