Abhijeet Bhatt
Abhijeet Bhatt

Reputation: 57

Exception Handling, C#

I came across this situation however I don't know how do I handle this exception when the user enters a number outside of the index of the string or any other datatype. In that condition I want the program to display the exception and go back to the first if statement. The code must be as basic as possible as I have just started learning programming. I know the use of 'Try Catch' (or so I think) but I can't determine how to use it here.

choice = int.Parse(Console.ReadLine());
if (arr[choice] != 'X' && arr[choice] != 'O')
{
  if (player % 2 == 0)
  { 
    arr[choice] = 'O';
    player++;
  }
  else
  {
    arr[choice] = 'X';
    player++;
  }
}
else
{
    Console.WriteLine("Sorry the row {0} is already marked with {1}", choice,arr[choice]);
Console.WriteLine("\n");
}

Upvotes: 2

Views: 117

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

You can do it like this:

int choice;
bool isValidChoice = int.TryParse(Console.ReadLine(), out choice) && choice >= 0 && choice < arr.Length;
if (isValidChoice && arr[choice] != 'X' && arr[choice] != 'O') {
  if (player % 2 == 0) {
    arr[choice] = 'O';
    player++;
  } else {
    arr[choice] = 'X';
    player++;
  }
} else if (!isValidChoice) {
  Console.WriteLine("Sorry you have not entered a valid in-range integer");
} else {
  Console.WriteLine("Sorry the row {0} is already marked with {1}", choice, arr[choice]);
  Console.WriteLine("\n");
}

Some explanations:

  1. int.TryParse, is effectively the equivalent of
int choice;
bool isValid = false;
try {
    choice = int.Parse(Console.ReadLine());
    isValid = true;
} catch {}
  1. && will only be evaluated only when the previous statement is correct. So in choice >= 0 && choice < arr.Length the choice < arr.Length will only be checked if the choice >= 0 is correct
  2. If you want to retry as long as the input is invalid. Try using the while(!isValidChoice) loop. I will not tell you how, as I think it will be a good learning experience.

Upvotes: 2

Related Questions