重构以删除try / catch

时间:2010-01-11 22:14:41

标签: c# exception-handling refactoring

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

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的标题编辑 - &gt;我本来应该发布更多的信息,这本来就是“一起摆脱try / catch是最好的”。所以考虑到这一点,我改变了标题。

6 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:4)

警告,未经测试!

public int ChooseNextColor(int numColors)
{
    while (true)
    {
        Console.Write("Please enter your next color selection: ");
        string input = Console.ReadLine();
        int color;
        if (!int.TryParse(input, out color) || color > numColors || color < 0)
        {
            Console.WriteLine("Unrecognized input: " + input);
            Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
        }
        else
        {
            return color;
        }
    }
}

答案 2 :(得分:2)

.NET提供TryParse就是出于这个原因。

答案 3 :(得分:1)

您可以使用Int32.TryParse()

if (nextColor > numColors || nextColor < 0) 
    {
        Console.WriteLine("Unrecognized input: " + input);
        Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
        return null;
    }

答案 4 :(得分:1)

如果要避免异常,则应使用int.TryParse方法而不是Convert.ToInt32()。

答案 5 :(得分:1)

    public Int32 ChooseNextColor(Int32 numColors)
    {
        var success = false;
        while (!success)
        {
            Console.Write("Please enter your next color selection: ");
            int nextColor;
            var input = Console.ReadLine();
            success = int.TryParse(input, out nextColor);

            if (success && nextColor > 0 && nextColor < numColors) return nextColor;

            Console.WriteLine("Unrecognized input: " + input);
            Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
        }
        throw new ApplicationException("The thing that should not be.");
    }