I understand it doesn't throw an Exception and because of that it might be sightly faster, but also, you're most likely using it to convert input to data you can use, so I don't think it's used so often to make that much of difference in terms of performance.
Anyway, the examples I saw are all along the lines of an if/else block with TryParse
, the else returning an error message. And to me, that's basically the same thing as using a try/catch block with the catch returning an error message.
So, am I missing something? Is there a situation where this is actually useful?
C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".
Apart from the performance aspect that you mentioned yourself, there's also a semantic difference:
Using try/catch is meant for exceptional circumstances. Inputting invalid data is something you expect, not something exceptional.
It's pretty much as simple as this: Use Parse
if you want an exception when you encounter invalid data; use TryParse
if you don't. Your question seems, therefore, to be:
Why would you not want an exception if data is invalid?
Exceptions should only be used for exceptional cases, and the data being invalid might not be an exceptional case. Maybe you're writing a data cleansing program that's expecting to get invalid data and will try to infer what a reasonable value is when the data is invalid. Maybe the data isn't all that important and you can just skip the record that contains it.
It depends on context, and having the choice of Parse
and TryParse
methods lets you choose the appropriate parsing mechanism for yours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With