【问题标题】:What Exception should be thrown when an ADO.NET query cannot retrieve the requested data?当 ADO.NET 查询无法检索到请求的数据时应该抛出什么异常?
【发布时间】:2010-09-12 09:51:18
【问题描述】:

为了向我们的应用程序添加一些参数验证和正确的使用语义,我们正在尝试向我们的 .NET 应用程序添加正确的异常处理。

我的问题是:当在 ADO.NET 中抛出异常时,如果特定查询没有返回数据或找不到数据,我应该使用什么类型的异常?

伪代码: (阅读,不要检查代码的语义,我知道它不会编译)

public DataSet GetData(int identifier)
{
    dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString();
    DataSet ds = dataAdapter.Fill(ds);
    if (ds.table1.Rows.Count == 0)
        throw new Exception("Data not found");

    return ds;
}

【问题讨论】:

    标签: .net sql exception ado.net


    【解决方案1】:

    就 ADO.net 而言,返回零行的查询不是错误。如果您的应用程序希望将此类查询视为错误,则应通过从 Exception 继承来创建自己的异常类。

    public class myException : Exception
    {
       public myException(string s) : base() 
       {
          this.MyReasonMessage = s;
       }
    }
    
    public void GetData(int identifier)
    {
        dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString();
        DataSet ds = dataAdapter.Fill(ds);
        if (ds.table1.Rows.Count == 0)
            throw new myException("Data not found");
    }
    

    【讨论】:

    • 继承自 ApplicationException,这是 Microsoft 推荐的用于派生自定义异常的类。
    • 不再是:“您应该从 Exception 类而不是 ApplicationException 类派生自定义异常。您不应在代码中抛出 ApplicationException 异常,并且不应捕获 ApplicationException 异常,除非您打算重新抛出原来的异常。” -msdn.microsoft.com/en-us/library/…
    【解决方案2】:

    您确实应该定义自己的异常:DataNotFoundException。

    你不应该使用基本类 Exception,因为当你在调用代码中捕获它时,你会写类似

    try
    {
         int i;
         GetData(i);
    
    }
    catch(Exception e) //will catch many many exceptions
    {
        //Handle gracefully the "Data not Found" case;
        //Whatever else happens will get caught and ignored
    }
    

    仅捕获您的 DataNotFoundEXception 只会获得您真正想要处理的情况。

    try
    {
         int i;
         GetData(i);
    
    }
    catch(DataNotFoundException e) 
    {
        //Handle gracefully the "Data not Found" case;
    } //Any other exception will bubble up
    

    有一个类名为 SqlException,当 SQL 引擎出现问题时,最好不要让你的业务逻辑超载它

    【讨论】:

      【解决方案3】:

      MSDN guidelines 状态:

      • 考虑抛出驻留在系统命名空间中的现有异常,而不是创建自定义异常类型。

      • 如果您遇到的错误条件可以通过与任何其他现有异常不同的方式以编程方式处理,请创建并抛出自定义异常。否则,抛出现有异常之一。

      • 不要为了团队的异常而创建和抛出新异常。

      没有硬性规定:但如果您有不同的处理此异常的方案,请考虑创建自定义异常类型,例如 DataNotFoundException as suggested by Johan Buret。

      否则,您可能会考虑抛出现有异常类型之一,例如 System.Data.DataException 甚至可能是 System.Collections.Generic.KeyNotFoundException。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-01
        • 2015-05-12
        • 1970-01-01
        • 1970-01-01
        • 2016-01-22
        • 1970-01-01
        • 1970-01-01
        • 2020-08-21
        相关资源
        最近更新 更多