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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…