This question already has answers here:
What is ApplicationException for in .NET?
                                
                                    (3个答案)
                                
                        
                                2年前关闭。
            
                    
我想知道是否建议在用户违反某些业务规则时使用ApplicationException返回应用程序错误。例如:

public void validate(string name, string email)
{
    int count1 = (from p in context.clients
        where (p.name == clients.name)
        select p).Count();

    if (count1 > 0)
        throw new ApplicationException("Your name already exist in the database");

    int count2 = (from p in context.clients
        where (p.email == clients.email)
        select p).Count();

    if (count2 > 0)
        throw new ApplicationException("Your e-mail already exist in the database");
}


这是好是坏的策略?如果不是,哪种方法更好?

最佳答案

在您的代码示例中,最好抛出一个ArgumentNullException更有意义。 ApplicationException并未真正向调用者提供有关异常含义的任何指示。

至于对有效电子邮件的最后检查,最好是ArgumentException或从Argument异常继承的自定义异常类。

 public void update(string name, string email)
    {
        if (string.IsNullOrEmpty(name))
        {
            throw new ArgumentNullException(nameof(name), "Type your name");
        }

        if (string.IsNullOrEmpty(email))
        {
            throw new ArgumentNullException(nameof(email), "Type your e-mail");
        }

        if (isValidEmail(email))
        {
            throw new ArgumentException(nameof(name), "Invalid e-mail");
        }

        //Save in the database
    }

关于c# - 使用ApplicationException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32854311/

10-11 22:33