0
try
{
    for (int i = 0; i < 4; i++)
    {
        playerGuess[i] = int.Parse(Console.ReadLine()); //says this is the error
    }
}
catch (Exception ex)
{
    Console.WriteLine("{0} Exception caught", ex);
    Console.Read();
}

I run this code, and for some reason, it outputs the following errors:

   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
   at System.Convert.ToInt32(String value)

I tried fixes I've seen on another thread like this, but I can't get them to work. any ideas?

7
  • what you input? Commented Apr 26, 2020 at 21:28
  • Can you provide the data stored in playerGuess Commented Apr 26, 2020 at 21:29
  • @Muhammad Literally nothing. Commented Apr 26, 2020 at 21:31
  • @urlreader I didn't input anything, it prompted these errors before I could do anything. Commented Apr 26, 2020 at 21:32
  • And your input in Console.Readline ? Commented Apr 26, 2020 at 21:32

1 Answer 1

3

int.Parse() will fail with that exception if the value you provide it is not capable of being converted to an int, and as written you have no checks on the string being read from the console to verify that is the case before passing it to the method.

You can use int.TryParse() instead, which gives you a bit more control over how to handle a failure by returning a boolean indicating success. You might present an error message instead, and ask the user to resubmit.

string input = Console.ReadLine();
int result;

if(int.TryParse(input, out result)) // TryParse returns a boolean showing whether the parse worked
{
   // then perform your behavior safely
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.