关于 using/try/catch 的真正编码约定 [英] True coding convention about usings/try/catches

查看:29
本文介绍了关于 using/try/catch 的真正编码约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我得到了这个代码:

Let's assume i got this code:

internal static bool WriteTransaction(string command)
{
    using (SqlConnection conn = new SqlConnection(SqlConnectionString))
    {
        try
        {
            conn.Open();

            using (SqlCommand cmd = new SqlCommand(command, conn))
               cmd.ExecuteNonQuery();
        }
        catch { return false; }
    }

    return true;
}

好吧,我已经将 conn 的 using 放在 try/catch 子句之外,因为 SqlConnection 的构造函数将不抛出任何异常(正如它所说).因此,conn.Open() 在子句中,因为它可能会抛出一些异常.

Well, i have placed conn's using outside the try/catch clause because SqlConnection's constructor will not throw any exception (as it says). Therefore, conn.Open() is in the clause as it might throw some exceptions.

现在,这是正确的编码方法吗?看:SqlCommand 的构造函数也不会抛出exceptinos,但是为了减少代码,我将它与 cmd.ExecuteNonQuery() 一起放在 try 中/捕获.

Now, is that right coding approach? Look: SqlCommand's constructor does not throw exceptinos either, but for the code reduction i've placed it along with cmd.ExecuteNonQuery() both inside the try/catch.

或者,

也许这个应该在那里?

internal static bool WriteTransaction(string command)
{
    using (SqlConnection conn = new SqlConnection(SqlConnectionString))
    {
        try { conn.Open(); }
        catch { return false; }

        using (SqlCommand cmd = new SqlCommand(command, conn))
            try { cmd.ExecuteNonQuery(); }
            catch { return false; }
    }

    return true;
}

(对不起我的英语)

推荐答案

除非你能以某种有意义的方式处理异常,否则不要捕捉它.相反,让它向上传播调用堆栈.

Unless you can handle the exception in some meaningful way, do not catch it. Rather, let it propagate up the call-stack.

例如,在什么情况下 SqlCommand ExecuteNonQuery() 会抛出异常?一些可能性是 sql 查询格式不正确、无法执行或您已失去与数据库服务器的连接.你不会想以同样的方式处理这些,对吧?

For instance, under what conditions can a SqlCommand ExecuteNonQuery() throw exceptions? Some possibilities are sql query that is improperly formed, cannot be executed or you've lost connection to the database server. You wouldn't want to handle these all the same way, right?

您应该考虑处理的一个异常是 SQLException 死锁(错误号 1205).

One exception you should consider handling is the SQLException deadlock (erro number 1205).

正如评论中指出的那样,您至少应该记录异常.

As was pointed out in a comment, at the very minimum you should be logging exceptions.

[顺便说一句,鉴于您显示的代码,WriteTransaction() 对于该方法来说可能是一个糟糕的名称.]

[BTW, WriteTransaction() is probably a poor name for that method, given the code you have shown.]

这篇关于关于 using/try/catch 的真正编码约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆