Controlling format exception without try-catch blocks

Viewed 55

Is there any way to catch format exception here besides using a try-catch statement? If user inputs anything more than a single character, it gives format exception. This is my code:

public void Menu()
{
    Console.WriteLine("Would you like to play RPS? y/n");
    char playOrNot = Convert.ToChar(Console.ReadLine());
    while(!validateChoice(playOrNot))
    {
        Console.WriteLine("Invalid! please re-enter selection");
        playOrNot = Convert.ToChar(Console.ReadLine());
    }
    if (playOrNot == 'Y' || playOrNot == 'y')
    {
        Console.Clear();
        PlayGame();
    }
}
public bool validateChoice(char playornot)
{
    if (char.ToUpper(playornot) != 'Y' && char.ToUpper(playornot) != 'N')
        return false;
    return true;
}
2 Answers

Instead of relying on exceptions for control-flow you should always try to avoid them in the first place. In your case you could do so by using Read instead of ReadLine. Thus you only read a single character:

Console.WriteLine("Would you like to play RPS? y/n");
char playOrNot = Convert.ToChar(Console.Read());
while(!validateChoice(playOrNot))
{
    Console.WriteLine("Invalid! please re-enter selection");
    playOrNot = Convert.ToChar(Console.Read());
}

There are several options.

1 Use strings instead:

public void Menu()
{
    Console.WriteLine("Would you like to play RPS? y/n");
    string playOrNot = Console.ReadLine();
    while(!validateChoice(playOrNot))
    {
        Console.WriteLine("Invalid! please re-enter selection");
        playOrNot = Console.ReadLine();
    }
    if (playOrNot.ToUpper() == "Y")
    {
        Console.Clear();
        PlayGame();
    }
}
public bool validateChoice(string playornot)
{
    return !"YN".Contains(playOrNot);
}

2 Use Console.ReadKey:

public void Menu()
{
    Console.WriteLine("Would you like to play RPS? y/n");
    char playOrNot = Console.ReadKey();
    while(!validateChoice(playOrNot))
    {
        Console.WriteLine("Invalid! please re-enter selection");
        playOrNot = Console.ReadKey();
    }
    if (char.ToUpper(playOrNot) == 'Y')
    {
        Console.Clear();
        PlayGame();
    }
}
public bool validateChoice(char playornot)
{
    return !"YN".Contains(char.ToUpper(playOrNot));
}

3 Use a simple method to get the char from ReadLine:

public void Menu()
{
    Console.WriteLine("Would you like to play RPS? y/n");
    char playOrNot = GetChar();
    while(!validateChoice(playOrNot))
    {
        Console.WriteLine("Invalid! please re-enter selection");
        playOrNot = Console.GetChar();
    }
    if (char.ToUpper(playOrNot) == 'Y')
    {
        Console.Clear();
        PlayGame();
    }
}
public bool validateChoice(char playornot)
{
    return !"YN".Contains(char.ToUpper(playOrNot));
}
public char GetChar()
{
    string line = Console.ReadLine();
    if (line.Length == 1)
        return line[0]; // first char of line
    return (char)0;
}
Related