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.

Answers


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):

select (int?)node;

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.


Need Your Help

Pinch Zoom - not able to keep the image position fixed on zooming

objective-c ios xcode image-zoom pinchzoom

I am new to iphone development. I want zoom an imageview , I am using the following code,

Autosuggestion is not working on my search engin

javascript ajax

I have implemented dbsight on my server. It is working fine. Just one option is missing: it is not showing me autosuggestion on the search result page like in the demo page:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.