[英].Net: What is your confident approach in “Catch” section of try-catch block, When developing CRUD operations?
我想知道在.Net中開發CRUD操作(特別是當您使用數據庫作為數據源時)在try-catch塊的catch部分中是否有任何自信的方法嗎?
那么,您對以下幾行有何看法?
public int Insert(string name, Int32 employeeID, string createDate)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = this._ConnectionString;
try
{
SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UnitInsert";
if (connection.State != ConnectionState.Open)
connection.Open();
SqlCommandBuilder.DeriveParameters(command);
command.Parameters["@Name"].Value = name;
command.Parameters["@EmployeeID"].Value = employeeID;
command.Parameters["@CreateDate"].Value = createDate;
int i = command.ExecuteNonQuery();
command.Dispose();
return i;
}
catch
{
**// how do you "catch" any possible error here?**
return 0;
//
}
finally
{
connection.Close();
connection.Dispose();
connection = null;
}
}
對於初學者,我將使用using語句。
我不會將0作為失敗返回。 您無法成功更新任何記錄,因此0將是有效的成功響應代碼。 使用-1清楚地表明出了點問題。 就個人而言,如果發生某些意外事件,我寧願拋出異常。
try
{
using (SqlConnection connection = new SqlConnection())
{
connection.Open();
using(SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UnitInsert";
SqlCommandBuilder.DeriveParameters(command);
command.Parameters["@Name"].Value = name;
command.Parameters["@EmployeeID"].Value = employeeID;
command.Parameters["@CreateDate"].Value = createDate;
return command.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
LogException(ex);
return either -1 or re throw exception.
}
我認為,這是完全錯誤的地方,然后再抓住您無法處理的任何東西。 讓異常冒出來,讓調用的應用程序實現它自己的錯誤處理。 如果您在此處捕獲並吞下異常,則對已安裝應用程序的調試將是噩夢。
只有抓住了您可以處理的東西,然后扔掉其他所有東西...
我會做一個
catch(Exception ex){
// log exception here and set return value
}
我喜歡通過將所有異常收縮為少數幾個來將DAL的API形式化,然后將實際的異常嵌套為InnerException
。
例如,不是調用者錯誤的所有數據庫異常都將引發一種類型的異常,作為調用者故障的所有數據庫異常(例如未選擇任何行,無效的PK,無效的數據)都將引發另一種類型的異常(或者也許甚至在異常類型之間有更細微的區別),還有一種與數據庫無關的東西的最后一種異常類型(完整性檢查,NullRef等),除了我無法處理的異常(例如OutOfMemoryException
)。
這樣,很容易捕獲我在DAL中引發的異常,並且InnerException
中仍然提供所有特定的詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.