有什么好的方法来重构它,使我的代码的行为相同,但没有整个抛出和捕捉我自己的异常?

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);
}

编辑:try/parse方法正是我想要的。
作为对john标题edit的回应->我应该先发布更多的信息,这将是“摆脱try/catch all是最好的”。因此,考虑到这一点,我改变了标题。

最佳答案

尝试

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();
}

09-11 19:34