Search code examples
c#.netvisual-studio-2010debuggingxmlreader

What does Visual Studio 2010 debugger do with the XmlException in XmlReader.Read?


I run this sample application:

class Program
{
    static void Main()
    {
        var reader = System.Xml.XmlReader.Create(@"C:\nonXml.txt");
        while (reader.Read()) { }
        System.Console.WriteLine("Ok");
        System.Console.ReadKey();
    }
}

nonXml.txt is a one-line text file with non-xml content.

When I run the application without the debugger, reader.Read throws an expected XmlException and the application exits with error. When I run it with the debugger (F5 in Visual Studio), debugger signals the exception but after pressing F5 (Continue) the application unexpectedly continues normally and writes "Ok".

What's going on in the debug mode in this case?


Solution

  • I think I understand your confusion. When you debug and visual studio handles exception it stops at error line. In normal situation pressing F5 run again the same line and you are in loop of errors. But in your case you have only one exception and then VS run as nothing happened.

    I think you realize now what is happening. First attempt on reader.Read() read file for xml data and move index in stream to the end of file. After you pressing F5 you run this line again and reader.Read() return false because EOF. That's it.

    In normal run (without debugging) your application die on first uncatched error and nothing else is happening.

    Bonus sample as a proof (paste is instead of your while loop):

    try
    {
        while (reader.Read()) { }
    }
    catch (Exception)
    {
        Console.Out.WriteLine("We have excpetion, this is wrong file");
    }
    
    while (reader.Read()) { } // we have eof so we don't get exception only false