2

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");
}
5
  • 1
    You shouldn't be using exceptions for flow control. What you should do is check if the input is correct, and if it's not, prompt the user to input again. You know users can enter undesirable input, so you should handle that case instead of try catch Commented Feb 7, 2021 at 6:43
  • How do i stop the program from terminating if the use enter any other datatype?@Zer0 Commented Feb 7, 2021 at 6:49
  • I would need to see more code. Minimal code that encapsulates the problem. I have no idea how you're getting your input, for example. It looks like you're writing Tic-Tac-Toe. But probably the important part is where you get the user input really. Commented Feb 7, 2021 at 6:51
  • choice = int.Parse(Console.ReadLine()); just before the If statement @Zer0 Commented Feb 7, 2021 at 6:56
  • If you don't want to use exception, use int.TryParse instead of int.Parse and compare choice against the allowed range 0 ... arr.Length - 1 before accessing an array element. Commented Feb 7, 2021 at 6:59

1 Answer 1

2

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

7 Comments

This can still throw if choice is < 0 or >= arr.Length
True, I fixed that too.
Looks good, but would be more useful to show how to prompt the user for input if it's incorrect. That's up to OP, but since this question is for beginner's it would be really useful to see that, imho.
I added some explanations and an excerisice too, to help him with learning.
Good added info, however int.TryParse does not throw exceptions (even internally). I dislike that comparison. Here's the code.
|

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.