XDocument.Load(XmlReader)可能的exception

调用XDocument.Load(XmlReader)时可能抛出的exception有哪些? 当文档无法提供关键信息时,很难遵循最佳实践(即避免使用通用的try catch块)。

提前感谢你的帮助。

MSDN说:LINQ to XML的加载function是基于XmlReader构建的。因此,您可能会捕获XmlReader抛出的任何exception。 创建重载方法和读取和解析文档的XmlReader方法。

http://msdn.microsoft.com/en-us/library/756wd7zs.aspx ArgumentNullException和SecurityException

编辑:MSDN并不总是说真的。 所以我用reflection器分析了Load方法代码并获得了如下结果:

 public static XDocument Load(XmlReader reader) { return Load(reader, LoadOptions.None); } 

方法Load是调用方法:

 public static XDocument Load(XmlReader reader, LoadOptions options) { if (reader == null) { throw new ArgumentNullException("reader"); //ArgumentNullException } if (reader.ReadState == ReadState.Initial) { reader.Read();// Could throw XmlException according to MSDN } XDocument document = new XDocument(); if ((options & LoadOptions.SetBaseUri) != LoadOptions.None) { string baseURI = reader.BaseURI; if ((baseURI != null) && (baseURI.Length != 0)) { document.SetBaseUri(baseURI); } } if ((options & LoadOptions.SetLineInfo) != LoadOptions.None) { IXmlLineInfo info = reader as IXmlLineInfo; if ((info != null) && info.HasLineInfo()) { document.SetLineInfo(info.LineNumber, info.LinePosition); } } if (reader.NodeType == XmlNodeType.XmlDeclaration) { document.Declaration = new XDeclaration(reader); } document.ReadContentFrom(reader, options); // InvalidOperationException if (!reader.EOF) { throw new InvalidOperationException(Res.GetString("InvalidOperation_ExpectedEndOfFile")); // InvalidOperationException } if (document.Root == null) { throw new InvalidOperationException(Res.GetString("InvalidOperation_MissingRoot")); // InvalidOperationException } return document; } 

具有例外可能性的行被评论

我们可以得到下一个exception:ArgumentNullException,XmlException和InvalidOperationException。 MSDN说您可以获得SecurityException,但也许您可以在创建XmlReader时获得此类exception。

XmlReader.Create(Stream)允许两种类型的exception: [src]

 XmlReader reader; // Do whatever you want try { XDocument.Load(reader); } catch (ArgumentNullException) { // The input value is null. } catch (SecurityException) { // The XmlReader does not have sufficient permissions // to access the location of the XML data. } catch (FileNotFoundException) { // The underlying file of the path cannot be found } 

看起来在线文档没有说明它抛出了哪些例外……太糟糕了。 使用FileInfo实例,并使用Exists方法确保文件确实存在 ,您将使用FileNotFoundException来节省一些麻烦。 这样你就不必捕获那种类型的exception。 [编辑]重新阅读你的post后,我忘了你注意到你正在传入一个XML阅读器。 我的回复是基于传入代表文件的字符串(重载方法)。 鉴于此,我会(就像回答你的问题的另一个人也有一个很好的答案)。

鉴于缺少的exception列表,我建议使用格式错误的XML制作一个测试文件并尝试加载它以查看真正被抛出的exception类型。 然后处理这些案件。