We all know the effects that lots of thrown exceptions can have over the performance of our applications, thus, we should stay away from things like using exceptions for control flow.
After this statement I must confess that when coding I didn’t care that much about this. I’ve been working mostly on Java platform but lately I was doing it on .NET platform and just found out this handy method: public static bool TryParse(string s,out int result)
,which allows you to transform a String into int whithout raise an exception. From that moment on, I’m keeping on using it. I just wanted to ask you about your preferences regarding the use of public static bool TryParse(string s,out int result) or public static int ToInt32(string value).
And from the point of view of Java, just pointing that it’s missing such a similar method, despite we could get it through things like:
boolean isInteger = Pattern.matches("^\d*$", myString);
Thanks.
Yes, Java is missing a similar method, although without
outparameters it’s actually pretty difficult to express (while wanting to return a primitive). Generally, though, in C# you should useTryParseif you expect the value to not be an integer sometimes, andToInt32otherwise; this way the “exceptional” situation is treated as such.In particular if performance is your main reason for wanting
TryParse, the regex matches method you post is considerably worse. The performance “expense” of Exceptions (which is, in reality, very minimal) is dwarfed by how much using them wrongly can fuzz easy understanding of control flow.