Why doesn't System.Xml.XmlReader.GetAttribute(String)
throw an exception if the attribute is not found?! It seems ridiculous and dangerous at first sight.
Asked
Active
Viewed 1,156 times
2 Answers
3
Because there's nothing "exceptional" about not finding a specified attribute. What if it's optional? Would you then be relying on thrown exceptions to control your program flow?
This isn't good practice - you should simply check the return value for null before using it.

Chris McAtackney
- 5,192
- 8
- 45
- 69
-
1+1 - right on...exceptions shouldn't be used for testing conditions – David Hoerster Jan 26 '12 at 13:26
-
And what about XmlReader.ReadElementContentAsString(string, string) for example? It throws exception in this case. Or element cannot be optional unlike attribute? – groaner Jan 26 '12 at 13:34
-
By the way, I'm certainly not going to use exceptions for testing conditions. All of my attributes are required. I think it is much more frequent situation than optional attributes – groaner Jan 26 '12 at 13:38
-
"All of my attributes are required. I think it is much more frequent situation than optional attributes". I think you are wrong. Probably neither of us has any quantitative data to use as evidence. – Michael Kay Jan 26 '12 at 16:11
-
OK, I was wrong. I thought XmlReader has something like bool HasAttribute(string name) to determine the presence of the attribute. And without such method null from GetAttribute() - it is the only option ) – groaner Jan 26 '12 at 18:04
-
You probably want to write an XSD to validate your XML document against if correctness of the XML is an issue. – Chris J Jan 26 '12 at 22:31
-
Thanks, but it is just configuration file containing data serialized by me. I HOPE that it will be correct all the time ))) – groaner Jan 27 '12 at 01:55
-
@groaner: Slightly on a tangent, but have you thought about using XDocument instead of XmlReader? See the accepted answer on this question for some nice examples of the advantages of doing so; http://stackoverflow.com/questions/904129/how-to-use-xmlreader-class – Chris McAtackney Jan 27 '12 at 10:20
1
Exceptions shouldn't be used for control-flow. As Chris McAtackney stated, what if the attribute is optional? Using exceptions for control flow adds overhead when exceptions are caught due to a missing attribute. It's better and more efficient to just check for an empty string.

David Hoerster
- 28,421
- 8
- 67
- 102