C# – Strange unhandled XmlException behaviour

cexceptionxml

In reading this recent question about an unhandled XmlException, I tried to reproduce it in both a .NET 2.0 and 3.5 console application.

However in my code it behaves exactly as expected, the XmlDocument.Load method throws an XmlException because the source xml file contains a NULL character.

So, why does the Load statement in the following code (from that example), not throw an XmlException? Even more to the point, why is the XmlException not handled by the valid try block surrounding the SelectNodes() method call?

While I am guessing there may be some sort of lazy loading / caching going on internally, isn't this sort of behavior very unintuitive and confusing?

(The earlier question clearly shows a screenshot of the debugger complaining that SelectNodes() has thrown an XmlException but that it is unhandled???)

    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);
    }

Best Answer

The exception is always thrown by XmlDocument.Load as expected.

It's just that sometimes the debugger gets the line number wrong. In my experience, the next line of code incorrectly being highlighted as the thrower of an exception is not uncommon.

You can see this in the screenshots: the ASP error page correctly shows that XmlDocument.Load is the thrower, NOT the SelectNodes statement.

Related Topic