SBoss
SBoss

Reputation: 9215

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.

Upvotes: 2

Views: 125

Answers (2)

CodesInChaos
CodesInChaos

Reputation: 108800

I assume the service usually returns valid data, but I'd still try to guard against failure in an external component. If the service is under your own control and you are very sure it will never return invalid data, you can simply use Parse and be done. But if it's not under your control, handling failures gracefully is nice.

I'd put a catch clause at the outermost level of the code that handles the parsing. And translate any parse error into a generic "invalid data from service" exception with the original exception as inner exception.

Then the calling code can handle that one exception, so it doesn't shut down your whole application.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062790

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.

Upvotes: 2

Related Questions