Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't seem to handle XMLException?

I have the following code in one of our projects webpages:

            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(File.FullName);

            //work through each print batch in this queue file
            try
            {
                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);
            }

It basically takes an xml batch file and loads it up as an object, ready to be processed.

It's been working fine, until recently when one of the XML files was found to contain a null character (which is invalid in XML).

When it tries to process this "dudd" file, we get the following exception:

alt text http://blog.ianmellor.co.uk/images/xml_err.jpg

Ok so far.. but when we then try to "continue" or "step over", I expect it to flow into the catch block. However, it doesn't; we simply get the red screen of death:

alt text http://blog.ianmellor.co.uk/images/xml_err2.jpg

What am I doing wrong?

like image 430
Sk93 Avatar asked Sep 10 '09 10:09

Sk93


2 Answers

It is because you have not written

xDoc.Load(File.FullName);

inside the try block. That is the reason why the exception was not handled.

like image 58
rahul Avatar answered Nov 07 '22 03:11

rahul


The other answer about putting Load() inside the try block is right, but doesn't actually explain why SelectNodes() "appears" to be throwing an XmlException that is not being caught.

The actual answer is that the debugger is confused/out of sync with your source code and is actually showing the wrong line as causing the exception.

It should really be pointing to the xDoc.Load(File.FullName); , in which case it would be clear that this call should be inside the try block.

Why? Notice the XmlLoader.LoadNode() in the last line of the stack trace. In .NET Reflector you can see that the XmlDocument.Load() method (deep in it's bowels) calls the LoadNode() method.

However, also in reflector, it can be seen that the SelectNodes() method does not call LoadNode() anywhere in it's internal implementation.

So according to the stack trace, the exception cannot have been caused by SelectNodes().

I've seen the debugger get confused like this before when a code change is made and debugging started, but the debugging symbols have not been updated correctly. Try cleaning and re-building your solution to refresh the debugging symbols.

like image 42
Ash Avatar answered Nov 07 '22 03:11

Ash