Reputation: 1
Can someone please help me to know why below piece of code giving me Overflow exception even if I use long and double datatype of variable numValue: tring[] inputValues = new string[] { "3", "9999999999", "0", "2" };
foreach (string inputValue in inputValues)
{
long numValue = 0;
try
{
numValue = int.Parse(inputValue);
}
catch (FormatException)
{
Console.WriteLine("Invalid readResult. Please enter a valid number.");
}
catch (OverflowException)
{
Console.WriteLine("The number you entered is too large or too small.");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
I tried changing the data type of numValue variable.
Upvotes: 0
Views: 12
Reputation: 3276
You're using int.Parse
, which only supports the signed 32-bit integer limits. Even if you're then assigning that result into a long
(or double
) variable, int.Parse
itself will still overflow.
Change your code to use long.Parse
or double.Parse
, depending on if you want floating-point numbers or not.
...
long numValue = 0;
try
{
numValue = long.Parse(inputValue);
}
catch (FormatException)
{
...
Upvotes: 0