Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ApplicationException的使用_C#_Asp.net_Asp.net Mvc_Design Patterns - Fatal编程技术网

C# ApplicationException的使用

C# ApplicationException的使用,c#,asp.net,asp.net-mvc,design-patterns,C#,Asp.net,Asp.net Mvc,Design Patterns,我想知道当用户违反某些业务规则时,是否建议使用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)

我想知道当用户违反某些业务规则时,是否建议使用
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"); 
}
这是一个好策略还是一个坏策略?如果不是,什么方法更好?

来自:

您应该从Exception类而不是ApplicationException类派生自定义异常。您不应该在代码中引发ApplicationException异常,也不应该捕获ApplicationException异常,除非您打算重新引发原始异常


一个简单的原因是.NET中还有其他从
ApplicationException
派生的异常类。如果您在代码中抛出
ApplicationException
,然后再捕获它,您可能还会捕获可能破坏应用程序的派生异常。

在您的代码示例中,最好抛出
ArgumentNullException
它更有意义
ApplicationException
不会真正向调用方提供异常含义的任何指示

对于有效电子邮件的最后一次检查,最好使用
ArgumentException
或从
Argument
exception继承的自定义异常类

 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
    }

实际上,您应该使用
Exception
在应用程序中通过派生来创建自定义异常。不过你也应该读一下


对于您来说,特定的示例案例参数验证应该抛出
ArgumentException
,如果它不存在,那么您可以为此创建一个从
Exception
类派生的自定义类

在System.Exception上抛出ApplicationException没有多大价值。对于这种类型的东西,通常使用
ArgumentException
,因为您正在验证方法参数。