我在数据访问层中有一个方法,可以将值写入给定 id 的特定字段。有人告诉我你不处理,而是抑制异常。怎么做才对?是否值得将此类结构包裹在 try-catch 中?如果在错误时抛出带有某些消息的新异常,是否会被认为是正常的?
public bool SetField(string table, string field, int id, string value)
{
try
{
string query = string.Format("update [{0}] set {1} = @value where id = @id;", table, field);
using (SqlConnection connection = new SqlConnection(_ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("@value", value);
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
return true;
}
}
catch (SqlException)
{
return false;
}
}
问题是 bool 不会告诉你
update表发生了什么table(你可以走很长时间并煮咖啡......然后猜测它的厚度)以便在该部分中找出它是必要的:或进一步“抛出”
throw异常并在调用站点处理(带有错误消息)或者进程在这个地方,例如这样:
或者抛出你自己的异常(这种情况很正常):
任务问题。
当然值得。这些操作更容易引起异常。
当然。