简体   繁体   English

我应该使用什么样的例外来“找不到记录”? (C#)

[英]What kind of exception should I use for “No Record Found” ? (C#)

I've got the following code which retrieves a records details when I click on a table grid: 我有以下代码,当我点击表格时,它会检索记录详细信息:

public ActionResult City(string rk)
{ 
    try
    {
        var city = _cityService.Get("0001I", rk);
        if (city == null)
        {
            throw new ServiceException("", "Error when fetching city " + rk);
        }
    }
}

What kind of exception should I use for this "no record found" problem? 我应该使用什么样的例外来解决这个“没有找到记录”的问题? I see there are different kinds of exception, but I am not sure which would be appropriate or even if I am coding this correctly. 我看到有不同类型的异常,但我不确定哪个是合适的,或者即使我正确编码。

KeyNotFoundException would be a reasonable choice, and would conform to the Microsoft guideline to: KeyNotFoundException是一个合理的选择,并且符合Microsoft指南

Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types. 考虑抛出驻留在System命名空间中的现有异常,而不是创建自定义异常类型。

However you could consider creating your own Exception type if (again from the Microsoft guidelines): 但是,您可以考虑创建自己的Exception类型(再次来自Microsoft指南):

... you have an error condition that can be programmatically handled in a different way than any other existing exceptions. ...您有一个错误条件,可以以与任何其他现有异常不同的方式以编程方式处理。

If you do create your own Exception , you should follow the guidelines for designing custom exceptions , eg you should make your Exception type Serializable. 如果您确实创建了自己的Exception ,则应遵循设计自定义异常准则 ,例如,您应该使您的Exception类型可序列化。

您应该创建自己的异常,在这种情况下可能会将其称为RecordNotFoundException

Creating your own exception is quite easy. 创建自己的异常非常简单。 Just make a class, give it a name, extend Exception or some other exception type, and provide the constructors that you need (just calling the base Exception constructors). 只需创建一个类,为其命名,扩展Exception或其他一些异常类型,并提供所需的构造函数(只需调用基本的Exception构造函数)。

If you want to add more, you can, but you often don't need to. 如果你想增加更多,你可以,但你经常不需要。

If you find yourself creating a number of exceptions for your project you may want to create a base exception type (that extends Exception) which all of your exceptions extend. 如果您发现自己为项目创建了许多例外,则可能需要创建一个基本异常类型(扩展Exception),所有异常都会扩展。 This is something you might do when writing a library. 这是您在编写库时可能会执行的操作。 It would allow someone to catch either a specific exception, or an exception thrown from your library, or any exception. 它允许某人捕获特定异常,或从库中抛出的异常,或任何异常。

public class MySuperAwesomeException : Exception
{
    public MySuperAwesomeException() : base() { }
    public MySuperAwesomeException(string message) : base(message) { }
    public MySuperAwesomeException(string message, Exception innerException)
        : base(message, innerException) { }
}

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

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