2013-06-20 26 views
5

在我的C#應用​​程序我用以下語句:保存XDocument時會發生什麼異常?

public void Write(XDocument outputXml, string outputFilename) { 
    outputXml.Save(outputFilename); 
} 

我怎樣才能找出Save方法可能會拋出哪些異常?最好在Visual Studio 2012中或者在MSDN文檔中。

XDocument.Save沒有給出任何參考。它適用於其他方法,例如File.IO.Open

回答

6

不幸的是,MSDN沒有關於XDocumentSystem.Xml.Linq命名空間拋出的異常的任何信息。

但這裏是儲蓄如何實現的:

public void Save(string fileName, SaveOptions options) 
{ 
    XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options); 
    if ((declaration != null) && !string.IsNullOrEmpty(declaration.Encoding)) 
    { 
     try 
     { 
      xmlWriterSettings.Encoding = 
       Encoding.GetEncoding(declaration.Encoding); 
     } 
     catch (ArgumentException) 
     { 
     } 
    } 

    using (XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings))  
     Save(writer);   
} 

如果你會越挖越深,你會看到有大量可能的例外。例如。 XmlWriter.Create方法可以拋出ArgumentNullException。然後創建XmlWriter,其中涉及FileStream創建。在這裏,你可以捕捉ArgumentExceptionNotSupportedExceptionDirectoryNotFoundExceptionSecurityExceptionPathTooLongException

所以,我想你不應該試圖捕獲所有這些東西。考慮到包裝的應用程序特定的異常任何異常,將其投入到更高水平的應用程序:

public void Write(XDocument outputXml, string outputFilename) 
{ 
    try 
    { 
     outputXml.Save(outputFilename); 
    } 
    catch(Exception e) 
    { 
     throw new ReportCreationException(e); // your exception type here 
    } 
} 

調用代碼只能抓ReportCreationException和記錄它,通知用戶等

1

如果MSDN沒有聲明任何我猜這個類不會拋出任何異常。雖然,我不認爲這個對象將負責將實際的文件寫入磁盤。因此,您可能會收到以下類別的例外情況:XDocument.Save();

爲了安全起見,我將捕獲所有異常並嘗試一些明顯的錯誤說明,請參見下文。

try 
{ 
    outputXml.Save("Z:\\path_that_dont_exist\\filename"); 
} 
catch (Exception e) 
{ 
    Console.WriteLine(e.Message); 
} 

在這裏,捕獲異常將捕獲任何類型的異常。

相關問題