繁体   English   中英

使用Assert时C#抛出异常?

[英]C# Throw Exception on use Assert?

我有一个系统,其中employeeId必须总是存在,除非存在一些潜在的问题。

我看到的方式是,我有两个选择来检查这段代码:

1:

public void GetEmployee(Employee employee)  
{  
   bool exists = EmployeeRepository.VerifyIdExists(Employee.Id);  
   if (!exists)   
   {   
     throw new Exception("Id does not exist");  
   }  
}    

或2:

public void GetEmployee(Employee employee)  
{  
  EmployeeRepository.AssertIfNotFound(Employee.Id);  
}  

选项#2在C#语言中是否可以接受?

我喜欢它,因为它很整洁,因为我不喜欢在类范围内查看“抛出新异常(”bla bla bla“)类型的消息。

通常,您应该只在特殊情况下抛出异常。 由于这种情况,抛出异常是正确的做法。

这取决于Assert意思。

您可以使用Debug.Assert (或Trace.Assert,如果您希望它也可以在发布模式下工作)。 然而,这不是那么有用,因为它会暂停程序并弹出一个对话框,直到用户按下某个东西。 这对于不受监控的系统来说并不是那么好。 所以我建议在大多数情况下投掷,尽管你可以决定如何对错误作出反应 - 停止程序,或者只是记录并尝试继续。

但是如果我们假设您的Assert方法检查其参数并可能抛出异常,那么我认为这是一种很好的方法。

事实上,举一个例子,在Jon Skeet的morelinq中使用了两种方法。 例如这里

public static IEnumerable<TSource> AssertCount<TSource>(
    this IEnumerable<TSource> source, 
    int count,
    Func<int, int, Exception> errorSelector)
{
    source.ThrowIfNull("source");
    if (count < 0) throw new ArgumentException(null, "count");
    errorSelector.ThrowIfNull("errorSelector");

    return AssertCountImpl(source, count, errorSelector);
}

使用例外,它是它们的用途 - 特殊情况。 所有标准的.NET库都使用这种处理这种情况的方法,所以从微软那里得到你的暗示。

断言背后的想法,正如我一直使用的那样,是在运行调试版本时它们是即时反馈。 发生在你脸上的那种事。 如果应用程序以这种方式设置,则记录到文件。

如上所述,例外用于处理异常行为。

我所做的,特别是项目生命周期的早期可能是这样的:

public void GetEmployee(Employee employee)  
{  
   bool exists = EmployeeRepository.VerifyIdExists(Employee.Id);  
   Debug.Assert( exists, "employee does not exist for id: " + Employee.Id );
   if (!exists)   
   {   
     throw new Exception("Id does not exist);  
   }  
}   

一旦处理了初始打嗝,也许可以解析Debug.Assert。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM