2014-03-05 35 views
0

我有一個問題,需要在catch塊中使用try/catch,但我讀到這不是最佳實踐。有沒有更好的方法來解決這個問題?嵌套try-catch語句的替代方法

 XmlDocument xmlDoc; 
     try 
     { 
      xmlDoc = DocumentLoad(filepath); 
     } 
     catch (XmlException) 
     { 
      try 
      { 
       xmlDoc = DocumentLoadXml(filepath); 
      } 
      catch (Exception) 
      {      
       throw; 
      } 
     } 

DocumentLoad(字符串文件路徑)使用XMLDocument.load方法(),其中,如果它拋出異常,我嘗試讀取文件,逸出的任何必要& <>「」,和負載用XmlDocument.LoadXml()。但是,這也可能會拋出異常。

我不是想先讀文件,如果有,因爲這可能並不需要無效字符看得十分熱衷。

+1

那麼,你重新拋出它,所以你很好;) –

+0

目標是通過一個文件列表,直到在加載時不拋出異常爲止? – Charlie

+0

爲什麼DocumentLoad工作/失敗,其中DocumentLoadXml不工作/失敗?那就是,爲什麼不嘗試並立即着手「最終」任務? – user2864740

回答

2

你有什麼理由不能這樣做嗎?

XmlDocument xmlDoc = null; 
try 
{ 
    xmlDoc = DocumentLoad(filepath); 
} 
catch (XmlException) { } 

if (xmlDoc == null) 
    xmlDoc = DocumentLoadXml(filepath); 

評論:

  • 第二的try/catch被消除,因爲你簡單地捕捉和投擲 - 如果你不是用它做任何事情,那麼請不要抓住它

  • 您有意識地忽略並忽略第一個XmlException - 這很好,但這意味着我們只需要測試一個空值xmlDoc並將其用作指示器,以便使用備用加載方法

+1

我喜歡這種方式比我想要的更好。我已經用其他代碼幾次完成了這個方法,但不知道爲什麼它沒有發生在我身上。下午編碼,沒有剩下的智力。謝謝您的幫助。 – jamesd7198

0

你可以在兩個區塊移到讓它們串聯起來,如果第一個沒有給你一個有效的文件,這隻會嘗試第二個加載方法。

XmlDocument xmlDoc = null; 
    try 
    { 
     xmlDoc = DocumentLoad(filepath); 
    } 
    catch (XmlException) 
    { 

    } 

    if(xmlDoc == null){ 
     xmlDoc = DocumentLoadXml(filepath); 
    } 
+2

如果他使用這種方法,則不需要重新拋出第二次嘗試/捕獲。 – Matthias247

+0

@ Matthias247這是沒有必要的 –

+1

@BakakNaffas:是的,但如果(xmlDoc == null)xmlDoc = DocumentLoadXml(filePath)將完全等價。 – Matthias247

3

那麼這是確定的,但在catch {throw;}是不必要的 - 這是默認的行爲:

XmlDocument xmlDoc; 
    try 
    { 
     xmlDoc = DocumentLoad(filepath); 
    } 
    catch (XmlException) 
    { 
     xmlDoc = DocumentLoadXml(filepath); // if this throws an exception it will be rethrown 
    } 

但我很好奇,爲什麼DocumentLoad將拋出一個異常,但DocumentLoadXml不會 - 你想使該方法適用於文件路徑和XML字符串?似乎有更好的方法來處理這個問題。你可不只是檢查數據,看看哪種方法是合適的?

+0

評論中的「rethrown」具有誤導性;如果發生嵌套異常,只是「拋出」(只有原始異常可能會在所提供的代碼中「重新拋出」) – user2864740

+0

如果存在非法字符,DocumentLoadXml使用Streamreader.ReadToEnd()嘗試轉義那些字符,然後嘗試使用Xml字符串加載。只是一個應急計劃。 – jamesd7198

+0

那麼爲什麼不直接使用'DocumentLoadXml'? –