C# differentiate exceptions

431 Views Asked by At

In C# I need to catch an XMLException but I also have to differentiate it, because it can be either Xml_InvalidRootData or Xml_UnexpectedEOF.

How can I achieve this?

Those strings I can only see in debugger with an alias of "ResString".

But I want to have multi-culture solution, so string comparison is something I want to avoid as much as possible.

HResults are the same.

1

There are 1 best solutions below

7
On

If you take a look at

https://referencesource.microsoft.com/#System.Runtime.Serialization/System/Xml/XmlExceptionHelper.cs

you'll see that throughout, there is a lot of work done to get a (possibly localized) error string, which is then the only argument to new XmlException.

As you correctly note, if you need to distinguish between different exception conditions to make some programmatic response, this is a whole lot of no help.

Since you do not want to examine the strings -- and that is a reasonable choice -- your best bet is probably to write your own XML parser that has the output you desire.

Consider the design of such a parser carefully. The output that you want is not the structured XML, but rather a detailed report explaining why it is not legal XML. Exceptions are a mechanism for handling exceptional situations; the designers of the XML parser considered malformed XML to be an exceptional situation; they thought this scenario should almost never happen. Since it almost never happens, and since when it does happen, there's nothing the program can do about it, there is no incentive to produce a detailed report that allows programmatic decisions to be made on the basis of what errors were detected.

But that is apparently not your situation; you have the opposite situation of the designers of the XML parser. You care about the error, and you wish to do something different depending on different errors, so the output of your parser should be the error report, not the XML syntax tree. It should not throw exceptions at all, because in your scenario, a malformed XML document is not exceptional; you expect it.

XML is not a particularly difficult language to lex and parse (provided you are not also trying to solve the problem of "is this document a valid instance of this schema?", which is a harder problem) so it should not take you long to produce an error-detecting lexer and parser, particularly since you have the source code of existing XML parsers to guide you. Good luck!