Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better: int.TryParse or try { int.Parse() } catch [closed]

I know.. I know... Performance is not the main concern here, but just for curiosity, what is better?

bool parsed = int.TryParse(string, out num); if (parsed) ... 

OR

try {     int.Parse(string); } catch () {     do something... } 
like image 545
renanleandrof Avatar asked Feb 09 '11 13:02

renanleandrof


People also ask

Why should one use TryParse instead of parse?

Parse() method throws an exception if it cannot parse the value, whereas TryParse() method returns a bool indicating whether it succeeded. However, TryParse does not return the value, it returns a status code to indicate whether the parse succeeded and does not throw exception.

What is the difference between int parse and int TryParse?

The difference in both methods is in the way they react when the string you are trying to convert to integer can't be converted to an integer. And in such a circumstance, the int. Parse() method will throw an exception whereas the int. TryParse() will return a boolean value of false.

What is difference between parse and TryParse?

The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter. If the string isn't in a valid format, Parse throws an exception, but TryParse returns false .


1 Answers

Better is highly subjective. For instance, I personally prefer int.TryParse, since I most often don't care why the parsing fails, if it fails. However, int.Parse can (according to the documentation) throw three different exceptions:

  • the input is null
  • the input is not in a valid format
  • the input contains a number that produces an overflow

If you care about why it fails, then int.Parse is clearly the better choice.

As always, context is king.

like image 152
Fredrik Mörk Avatar answered Oct 02 '22 01:10

Fredrik Mörk