Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring to remove try/catch

Any ideas on a good way to refactor this so that my code acts the same, but without the whole throwing and catching my own exception?

public Int32 ChooseNextColor(Int32 numColors)
{
    int? nextColor = null;

    while (nextColor == null)
    {
        Console.Write("Please enter your next color selection: ");
        string input = Console.ReadLine();

        try
        {
            nextColor = Convert.ToInt32(input);
            if (nextColor > numColors || nextColor < 0) 
                throw new ArgumentOutOfRangeException();
        }
        catch
        {
            nextColor = null;
            Console.WriteLine("Unrecognized input: " + input);
            Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
        }
    }

    return (nextColor.Value);
}

EDIT: The try/parse method is exactly what I am looking for.

In response to John's title edit -> I should have posted more information to begin with, and that would have been "getting rid of the try/catch all together is best". So with that in mind, I changed the title.

like image 668
Nick Larsen Avatar asked Nov 29 '22 20:11

Nick Larsen


1 Answers

Try

int nextColor;
input = Console.ReadLine();

while( ! Int32.TryParse( input, out nextColor ) 
       || nextColor > numColors 
       || nextColor < 0 )
{ 
    Console.WriteLine("Unrecognized input: " + input);
    Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
    input = Console.ReadLine();
}
like image 70
Paul Alexander Avatar answered Dec 15 '22 16:12

Paul Alexander