FormatException
-
Hello I´ve got a string and i would like to convert into an int but the problem is that when i don´t have an int an exception is throw (FormatException). How can i catch this expceion? The try{catch(Exception e) doen´t work. I use System.Convert.ToInt32(string). Thank you in advance, Borja Riesgo Juan
-
Hello I´ve got a string and i would like to convert into an int but the problem is that when i don´t have an int an exception is throw (FormatException). How can i catch this expceion? The try{catch(Exception e) doen´t work. I use System.Convert.ToInt32(string). Thank you in advance, Borja Riesgo Juan
-
Hello, Try catch should work in this case, but is not recommended. Instead you should use the int.Parse Method. All the best, Martin
Martin# wrote:
Instead you should use the int.Parse Method.
I think that you mean the int.TryParse method, as the int.Parse method doesn't offer anything over Convert.ToInt32. For framework 1.x you use double.TryParse with NumberStyles.Integer and then cast the value to int.
--- b { font-weight: normal; }
-
Martin# wrote:
Instead you should use the int.Parse Method.
I think that you mean the int.TryParse method, as the int.Parse method doesn't offer anything over Convert.ToInt32. For framework 1.x you use double.TryParse with NumberStyles.Integer and then cast the value to int.
--- b { font-weight: normal; }
Hello Guffa, Thank you for your info. I normaly work with double.TryParse(), but I never tried the NumberStyles.Integer. So I guess you would also recommend using double.TryParse plus cast to int, instead of try catch with Convert.ToInt32. So I think I'm going to change some of my code. So once again thanks for your help. All the best, Martin
-
Hello Guffa, Thank you for your info. I normaly work with double.TryParse(), but I never tried the NumberStyles.Integer. So I guess you would also recommend using double.TryParse plus cast to int, instead of try catch with Convert.ToInt32. So I think I'm going to change some of my code. So once again thanks for your help. All the best, Martin
Martin# wrote:
So I guess you would also recommend using double.TryParse plus cast to int, instead of try catch with Convert.ToInt32.
Yes. Exceptions are mainly for unexpected situations. If you expect something to happen, you should try to stop it before it happens. Another alternative is to use a regular expression to validate the string before you convert it. If you have verified that a string only contains digits and not more than fits in the range of an int, you can safely convert it to an int.
--- b { font-weight: normal; }