关于c#:使用ApplicationException

The use of ApplicationException

本问题已经有最佳答案,请猛点这里访问。

我想知道当用户违反某些业务规则时,是否建议使用ApplicationException返回应用程序错误。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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关好meaningful安恩将是黑莓。我真的ApplicationExceptiondoes not as to the indication给呼叫方的任何的例外是the means。P></

As for the valid for the last检查电子邮件,或者在自定义数据库类安ArgumentExceptionor from that inherits最佳Argument例外会好的。P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 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
    }

从msdn.microsoft.com HTTPS:/ / / /图书馆/ system.applicationexception销售额:P></

You should derive custom exceptions from the Exception class rather than the ApplicationException class. You should not throw an ApplicationException exception in your code, and you should not catch an ApplicationException exception unless you intend to re-throw the original exception.

一个简单的reason is that there are other的例外出现在从applicationexception源性类。如果你把你的尾巴applicationexception抓住它后,你也会吸引你可能打破了which源应用。P></


你应该知道Exception创建自定义数据库的使用在你的应用模式deriving from it.You should also read this答案虽然。P></

为你的房子validations argument特异性样品ArgumentException把if it should have的痕迹就不会有那么你可以在自定义类Exceptioncreated for this from衍生类。P></