[英]XDocument.Load(XmlReader) Possible Exceptions
調用XDocument.Load(XmlReader)
時可能拋出的異常是什么? 當文檔無法提供關鍵信息時,很難遵循最佳實踐(即避免使用通用的try catch塊)。
提前感謝你的幫助。
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);
}
方法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;
}
具有例外可能性的行被評論
我們可以得到下一個異常:ArgumentNullException,XmlException和InvalidOperationException。 MSDN說您可以獲得SecurityException,但也許您可以在創建XmlReader時獲得此類異常。
XmlReader.Create(Stream)
允許兩種類型的異常: [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來避免一些悲傷。 這樣你就不必捕獲那種類型的異常。 [編輯]重新閱讀你的帖子后,我忘了你注意到你正在傳入一個XML閱讀器。 我的回復是基於傳遞代表文件的字符串(重載方法)。 鑒於此,我會(就像回答你的問題的另一個人也有一個很好的答案)。
鑒於缺少的異常列表,我建議使用格式錯誤的XML制作一個測試文件並嘗試加載它以查看真正被拋出的異常類型。 然后處理這些案件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.