0

我想知道在.Net 中开发 CRUD 操作(特别是当您使用数据库作为数据源时)时,在 try-catch 块的 catch 部分中是否有任何自信的方法?

好吧,您对以下几行有何看法?

public int Insert(string name, Int32 employeeID, string createDate)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = this._ConnectionString;
        try
        {
            SqlCommand command = connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "UnitInsert";
            if (connection.State != ConnectionState.Open)
                connection.Open();
            SqlCommandBuilder.DeriveParameters(command);
            command.Parameters["@Name"].Value = name;
            command.Parameters["@EmployeeID"].Value = employeeID;
            command.Parameters["@CreateDate"].Value = createDate;
            int i = command.ExecuteNonQuery();
            command.Dispose();
            return i;
        }
        catch
        {
            **// how do you "catch" any possible error here?**
            return 0;
            //
        }
        finally
        {
            connection.Close();
            connection.Dispose();
            connection = null;
        }
    }
4

4 回答 4

3

对于初学者,我会使用 using 语句。

我不会返回 0 作为失败。您可以成功更新任何记录,因此 0 将是有效的成功响应代码。使用 -1 清楚地表明出了问题。就个人而言,我更愿意在发生预期的事情时抛出异常。

try
    { 
       using (SqlConnection connection = new SqlConnection())
        {

            connection.Open();         

            using(SqlCommand command = connection.CreateCommand())
            {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "UnitInsert";

                    SqlCommandBuilder.DeriveParameters(command);
                    command.Parameters["@Name"].Value = name;
                    command.Parameters["@EmployeeID"].Value = employeeID;
                    command.Parameters["@CreateDate"].Value = createDate;

                    return command.ExecuteNonQuery();
               }

        }
        }
        catch(Exception ex)
        {
          LogException(ex);
           return either -1 or re throw exception.
        }
于 2010-04-29T12:02:01.273 回答
2

在我看来,这是一个完全错误的地方来捕捉你不能在那里处理的任何东西。让异常冒泡并让调用应用程序实现它自己的错误处理。如果您在这里捕获并吞下异常,那么您对已安装应用程序的调试将是一场噩梦。

只抓住你能处理的东西,然后扔掉其他东西......

于 2010-04-29T12:02:13.643 回答
0

我会做一个

catch(Exception ex){
     // log exception here and set return value
}
于 2010-04-29T12:02:25.497 回答
0

我喜欢通过将所有异常收缩到少数几个并将实际异常嵌套为InnerException.

例如,不是调用者错误的所有数据库异常都会抛出一种类型的异常,所有调用者错误的数据库异常(例如没有选择行、无效的 PK、无效数据)都会抛出另一种类型的异常(或者可能甚至在异常类型之间有更细粒度的区别),最后一种异常类型用于与数据库无关的东西(健全性检查、NullRef 等),除了我无法处理的异常(例如OutOfMemoryException)。

这样就很容易捕获我在 DAL 中抛出的异常,并且所有具体的血腥细节仍然可以在InnerException.

于 2010-04-29T12:08:24.733 回答