.Net:你对《Catch》的信心是什么? try-catch 块的部分,开发 CRUD 操作时?

发布于 2024-08-30 22:23:13 字数 1238 浏览 6 评论 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;
        }
    }

I was wondering if there would be any confident approach for use in catch section of try-catch block when developing CRUD operations(specially when you use a Database as your data source) in .Net?

well, what's your opinion about below lines?

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;
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

醉酒的小男人 2024-09-06 22:23:13

首先我会使用 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.
        }

I would use a using statement for starters.

I wouldn't return 0 as a failure. You can successfully update no records and so 0 would be a valid success response code. Using -1 clearly shows that something went wrong. Personally, I would much rather throw an exception in the event something enexpected happened.

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.
        }
半寸时光 2024-09-06 22:23:13

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

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

In my opinion, this is wholly the wrong place to catch anything that you can't handle there and then. Let the exception bubble up and have the calling application implement it's own error handling. If you catch and swallow an exception here, your debugging for installed applications is going to be nightmarish.

Only ever catch what you can handle and throw everything else...

謌踐踏愛綪 2024-09-06 22:23:13

我会做一个

catch(Exception ex){
     // log exception here and set return value
}

I would do a

catch(Exception ex){
     // log exception here and set return value
}
挽容 2024-09-06 22:23:13

我喜欢通过将所有异常收缩到选定的几个异常并将实际异常嵌套为 InnerException 来形式化我的 DAL 的 API。

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

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

I like to formalize my DAL's API by contracting all exceptions to a select few, and nesting the actual exception as an InnerException.

For example, all database exceptions that aren't the callers fault would throw one type of exception, all database exception that are the callers fault (such as no rows selected, invalid PK, invalid data) would throw another type of exception (or perhaps even have a finer grained distinction between exception types), and one last exception type for stuff that is not related to the database (sanity checks, NullRef, etc), except for exceptions that I can't handle (such as OutOfMemoryException).

That way it is easy to catch the exceptions I throw in my DAL, and all the specific gory details are still available in InnerException.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文