在閱讀關於未處理的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