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)
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
SqlCommandExecuteNonQuery()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
SQLExceptiondeadlock (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.]