2011-07-06 51 views
3

如何正確讓異常冒泡?
如果我在調用方法時使用Try-Catch,只是在方法中拋出一個異常,例如不試圖捕獲它?
說明:這些方法是否做同樣的工作?讓一個異常冒泡

實施例1:

try 
{ 
    MyFileHandlingMethod();    
} 
catch (IOException ex) 
{ 
    string recfilepath = "... 
    string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString(); 
    File.AppendAllText(recfilepath, rectoadd); 
} 
catch (exception) 
{ 
    throw; 
} 
... 
MyFileHandlingMethod() 
{ 
    ... 
    TextReader tr2 = new StreamReader(nfilepath); 
    resultN = tr2.ReadLine(); 
    tr2.Close(); 
    ... 
} 

實施例2:

try 
{ 
    MyFileHandlingMethod();    
} 
catch (IOException ex) 
{ 
    string recfilepath = "... 
    string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString(); 
    File.AppendAllText(recfilepath, rectoadd); 
} 
catch (exception) 
{ 
    throw; 
} 
... 
MyFileHandlingMethod() 
{ 
    ... 
    try 
    { 
     TextReader tr2 = new StreamReader(nfilepath); 
     resultN = tr2.ReadLine(); 
     tr2.Close();    
    } 
    catch (Exception) 
    { 
     throw;  
    }  
    ... 
} 

回答

9

是的,這些2種方法具有相同的效果。

的catch /拋出塊象下面這樣,你不例外(如日誌)做任何事情的人,是沒有用的:

catch (Exception) 
{ 
    throw;  
} 

刪除它來清理,無論您的樣品英寸

而你的方法有另一個異常相關的問題,它不正確地釋放資源。該tr2.Close();屬於一個finally條款,但它更容易讓編譯器處理與一個using() {}塊:

void MyFileHandlingMethod() 
{ 
    ... 
    using (TextReader tr2 = new StreamReader(nfilepath)) 
    { 
    resultN = tr2.ReadLine();   
    } //tr2.Dispose() inserted automatically here   
    ... 
} 
2

首先,你應該與資源使用using塊,因爲這會採取正確關閉你的資源的護理。第二個例子幾乎沒用,因爲你在異常處理程序中不做任何工作。您應該刪除它,或者將其包裝在另一個異常中以添加一些信息。

2

是的,結果是一樣的。

但是,如果在閱讀時出現錯誤,兩者都將導致未關閉的流。您應該使用using塊或try ... finally以確保流被關閉:

using (TextReader tr2 = new StreamReader(nfilepath)) { 
    resultN = tr2.ReadLine(); 
} 

請注意,沒有在此代碼沒有Closeusing塊將處置StreamReader,這將關閉該流。

using塊被編譯爲一個try ... finally它用來確保StreamReader總是處置,但異常會冒泡到調用方法。

1

我建議你用你的第一個例子,這些變化:

try 
{ 
    MyFileHandlingMethod();    
} 
catch (IOException ex) 
{  
    string recfilepath = "..."; 
    string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ex.Message.ToString(); 
    File.AppendAllText(recfilepath, rectoadd); 
    throw; // rethrow the same exception. 
} 
// no need for second catch} 

你可能想重新拋出異常,一旦你已經登錄了,因爲你沒有做從錯誤中任何實際的恢復。