重构以删除try/catch

Nic*_*sen 4 c# refactoring exception-handling

关于重构这个问题的好方法的任何想法,以便我的代码行为相同,但没有整个抛出和捕获我自己的异常?

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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:try/parse方法正是我正在寻找的.

为了回应约翰的标题编辑 - >我应该发布更多的信息开始,这本来是"一起摆脱try/catch是最好的".所以考虑到这一点,我改变了标题.

Pau*_*der 14

尝试

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();
}
Run Code Online (Sandbox Code Playgroud)