What is better: int.TryParse or try { int.Parse() } catch [closed]
Solution 1:
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.
Solution 2:
Is it exceptional for the conversion to sometimes fail, or is it expected and normal that the conversion will sometimes fail? If the former, use an exception. If the latter, avoid exceptions. Exceptions are called "exceptions" for a reason; you should only use them to handle exceptional circumstances.
Solution 3:
If it is indeed expected that the conversion will sometimes fail, I like to use int.TryParse
and such neatly on one line with the conditional (Ternary) operator, like this:
int myInt = int.TryParse(myString, out myInt) ? myInt : 0;
In this case zero will be used as a default value if the TryParse method fails.
Also really useful for nullable types, which will overwrite any default value with null
if the conversion fails.