Parsing with TryParse or Parse when data is theoretically always correct?
I've looked at a few other questions (especially Parsing Performance (If, TryParse, Try-Catch)), and am thinking about the answers. Is it an abuse of exception handling if the exception shouldn't be thrown? Isn't that the whole point of it? Catching the error in the rare case that something goes wrong?
To be exact, I'm getting some xml data from a service and am wondering if I can assume that it is correct (with the .00000001% that a bit / something else got lost in the internet).
Edit I'll probably use Linq to XML, but the question still stands.
I look more at the scenario than the performance; if the expected behaviour is that it is valid, I generally use Parse (or ParseExact if available), and let the exception go. Unless I need to raise a specific error, in which case TryParse is handy.
If the data might be (say) an integer, then TryParse is preferable over Parse+catch.
With LINQ-to-XML: don't parse; instead, use the static conversion operators provided; so rather than:
... select int.Parse(node.Value);
you should use
... select(int) node;
this is even more important for things like DateTime, as it takes into account the standard XML formats. It also does the "expected" thing if the node doesn't exist (i.e. node is null):
will return a null value rather than throwing a NullReferenceException (which node.Value would do). There are static conversion operators for most expected data-types.