【发布时间】:2009-09-10 11:34:46
【问题描述】:
在阅读 this recent question 关于未处理的 XmlException 时,我尝试在 .NET 2.0 和 3.5 控制台应用程序中重现它。
但是在我的代码中,它的行为完全符合预期,XmlDocument.Load 方法会引发 XmlException,因为源 xml 文件包含 NULL 字符。
那么,为什么以下代码(来自该示例)中的 Load 语句不抛出 XmlException?更重要的是,为什么围绕 SelectNodes() 方法调用的有效 try 块没有处理 XmlException?
虽然我猜测内部可能会发生某种延迟加载/缓存,但这种行为是不是非常不直观和令人困惑?
(前面的问题清楚地显示了调试器的屏幕截图,它抱怨 SelectNodes() 抛出了 XmlException 但未处理???)
XmlDocument xDoc = new XmlDocument();
xDoc.Load(File.FullName);
//work through each print batch in this queue file
try
{
// This line throws an XmlException but is not handled by the catch!
XmlNodeList nodeList = xDoc.SelectNodes("Reports/PrintBatch");
foreach (XmlNode printBatch in nodeList)//xDoc.SelectNodes("Reports/PrintBatch"))
{
PrintBatch batch = new PrintBatch();
batch.LoadBatch(printBatch, File.Extension);
this.AddBatch(batch);
}
}
catch (XmlException e)
{
//this report had an error loading!
Console.WriteLine(e.Message);
}
【问题讨论】: