用户输入值验证和错误捕获级别

时间:2010-05-20 10:07:43

标签: c# exception error-handling

请问错误捕获代码应放在最低级别还是顶部,因为我不确定什么是最佳做法?我更喜欢放在底部,例如a,如

示例

   public static void Main(string[] args)
    {
        string operation = args[0];
        int value = Convert.ToInt32(args[1]);
        if (operation == "date")
        {
            DoDate(value);
        }
        else if (operation == "month")
        {
            DoMonth(value);
        }
    }
    public static void DoMonth(int month)
    {
        if (month < 1 || month > 12)
        {
            throw new Exception("");
        }
    }
    public static void DoDate(int date)
    {
        if (date < 1 || date > 31)
        {
            throw new Exception("");
        }
    }

或示例b

   public static void Main(string[] args)
    {
        string operation = args[0];
        int value = Convert.ToInt32(args[1]);
        if (operation == "date" && (date < 1 || date > 12))
        {
            throw new Exception("");
        }
        else if (operation == "month" && (month < 1 || month > 31))
        {
            throw new Exception("");
        }
        if (operation == "date")
        {
            DoDate(value);
        }
        else if (operation == "month")
        {
            DoMonth(value);
        }
    }
    public static void DoMonth(int month)
    {
    }
    public static void DoDate(int date)
    {
    }

2 个答案:

答案 0 :(得分:0)

有一个概念可以帮助您了解每个示例的后果

关注点分离

http://en.wikipedia.org/wiki/Separation_of_concerns

答案 1 :(得分:0)

这取决于。输入的技术验证应该在消费方法面前完成。技术验证意味着:有足够的参数吗?也许:他们有正确的“类型”吗?

信息验证应在解释输入之前完成。所以你符合OO原则。