0

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.

1 Answer 1

0

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)
{
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.