在阅读关于未处理的XmlException的this recent question时,我试图在.NET 2.0和3.5控制台应用程序中重现它。奇怪的未处理的XmlException行为
但是,在我的代码中,它的行为与预期的完全一样,XmlDocument.Load方法抛出一个XmlException,因为源xml文件包含一个NULL字符。
那么,为什么下面的代码中的Load语句(从该示例中),不抛出XmlException?更重要的是,为什么XmlException不是由围绕SelectNodes()方法调用的有效try块处理的?
虽然我猜测内部可能会有某种懒惰的加载/缓存,这种行为不是很不直观和令人困惑吗?
(早期的问题清楚地显示了调试抱怨的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);
}
你看起来是正确的。我在Reflector中检查了Load和SelectNodes的实现,它只出现Load calls XmlLoader.LoadNode()(如堆栈跟踪所示)。因此,调试符号可能与显示的代码不同步。 – Ash 2009-09-10 14:16:00