Rob*_*uch 5 c# exception-handling linq-to-xml
在我的C#应用程序中,我使用以下语句:
public void Write(XDocument outputXml, string outputFilename) {
outputXml.Save(outputFilename);
}
Run Code Online (Sandbox Code Playgroud)
如何找出Save方法可能抛出的异常?最好是在Visual Studio 2012中,或者在MSDN文档中.
XDocument.Save没有给出任何引用.它适用于其他方法,例如File.IO.Open.
不幸的是,MSDN没有任何关于System.Xml.Linq命名空间中抛出的异常XDocument以及许多其他类型的信息.
但这是如何实施节约:
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);
}
Run Code Online (Sandbox Code Playgroud)
如果你要深入挖掘,你会发现存在大量可能的异常.例如XmlWriter.Create方法可以抛出ArgumentNullException.然后它创建XmlWriter涉及FileStream创建.在这里,你可以捕捉ArgumentException,NotSupportedException,DirectoryNotFoundException,SecurityException,PathTooLongException等.
所以,我认为你不应该试图抓住所有这些东西.考虑将任何异常包装在特定于应用程序的异常中,并将其抛出到应用程序的更高级别:
public void Write(XDocument outputXml, string outputFilename)
{
try
{
outputXml.Save(outputFilename);
}
catch(Exception e)
{
throw new ReportCreationException(e); // your exception type here
}
}
Run Code Online (Sandbox Code Playgroud)
调用代码只能捕获ReportCreationException并记录它,通知用户等.
| 归档时间: |
|
| 查看次数: |
2204 次 |
| 最近记录: |