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 sur
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
Just try it. This code:
int.Parse("");
Throws a FormatException.
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.
If you can avoid it, do not code by exception!
The exception name you are looking for is called a FormatException
.
However, it would be smarter to first do a TryParse
on the object you are attempting to parse, e.g.
int value;
if(!int.TryParse("1", out value))
{
// You caught it without throwing an exception.
}
Exceptions are expensive. You should use int.TryParse. It will return the boolean false if the conversion fails.
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.