Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

c# - True coding convention about usings/try/catches

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

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.

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.

Or,

maybe this one should be there instead?

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

(sorry for my english)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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?

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...