'C# - failed parse exception?
I am writing a program in C#, and I want to catch exceptions caused by converting "" (null) to int. What is the exception's name?
EDIT: I'm not sure I can show the full code... But I'm sure you don't need the full code, so:
int num1 = Int32.Parse(number1.Text);
int num2 = Int32.Parse(number2.Text);
Solution 1:[1]
You are going to get a FormatException if a parse fails. Why not use int.TryParse instead?
Solution 2:[2]
As a side note, a simple way to find out the exception is to run it. When you encounter the error, it'll give you the exception name.
Solution 3:[3]
Let's have a look at the documentation (which is a much cleaner solution that "trying it out"):
public static int Parse(string s)
[...]
Exceptions:
ArgumentNullException: s is null.FormatException: s is not in the correct format.
This should answer your question. As others have already mentioned, maybe you are asking the wrong question and want to use Int32.TryParse instead.
Solution 4:[4]
Depends on what you're using to do the conversion. For example, int.Parse will throw ArgumentNullException, FormatException, or OverflowException. Odds are it's ArgumentNullException you're looking for, but if that's an empty string rather than a null reference, it's probably going to be FormatException
Solution 5:[5]
When the exception fires you can see it's type. The smart thing to do is handle that case and display a graceful message to your user if possible.
Solution 6:[6]
You're probably looking to get a System.InvalidCastException, although I think that'll depend on how you try to perform the conversion.
That said, wouldn't it be quicker/easier to simply write the code and try it yourself? Particularly as you haven't specified how you'll be performing the conversion.
Solution 7:[7]
Just try it. This code:
int.Parse("");
Throws a FormatException.
Solution 8:[8]
Exceptions are expensive. You should use int.TryParse. It will return the boolean false if the conversion fails.
Solution 9:[9]
Convert.ToInt32 does not throw a format exception ("input string is not in the correct format") on a null string. You can use that if it is acceptable for the result to be a 0 for a null string. (still pukes on empty string though)
string s = null;
int i = Convert.ToInt32(s);
But if you expect a number to be in the box, you should either use TryParse (as was suggested) or a Validator of some kind to inform the user that they need to enter a number.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Steve Danner |
| Solution 2 | |
| Solution 3 | Heinzi |
| Solution 4 | Randolpho |
| Solution 5 | Achilles |
| Solution 6 | Rob |
| Solution 7 | PetPaulsen |
| Solution 8 | Ashley Grenon |
| Solution 9 |
