Joe*_*ung 17 c# xml exception linq-to-xml
XDocument.Load(XmlReader)调用时可能抛出的异常有哪些?当文档无法提供关键信息时,很难遵循最佳实践(即避免使用通用的try catch块).
提前感谢你的帮助.
Nas*_*ova 21
MSDN说:LINQ to XML的加载功能是基于XmlReader构建的.因此,您可能会捕获XmlReader抛出的任何异常.创建重载方法和读取和解析文档的XmlReader方法.
http://msdn.microsoft.com/en-us/library/756wd7zs.aspx ArgumentNullException和SecurityException
编辑:MSDN并不总是说真的.所以我用反射器分析了Load方法代码并获得了如下结果:
public static XDocument Load(XmlReader reader)
{
return Load(reader, LoadOptions.None);
}
Run Code Online (Sandbox Code Playgroud)
方法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;
}
Run Code Online (Sandbox Code Playgroud)
具有例外可能性的行被评论
我们可以得到下一个异常:ArgumentNullException,XmlException和InvalidOperationException.MSDN说您可以获得SecurityException,但也许您可以在创建XmlReader时获得此类异常.
| 归档时间: |
|
| 查看次数: |
14586 次 |
| 最近记录: |