public bool AddEntity(int parentId,string description) { try { _connection.Open(); SqlCommand command = new SqlCommand(「INSERT Structure(Path,Description)」+ 「VALUES(」+ GetPath(parentId)+「.GetDescendant(」+ GetLastChildPath(parentId,1)+「,NULL),」+ description +「)」,_connection);異常處理 - 有沒有更好的方法?
if (command.ExecuteNonQuery() <= 0) _success = false;
command.Connection.Close();
if (_success)
{
return true;
}
throw new Exception("An error has occured whilst trying to add a entity");
}
catch (Exception ex)
{
AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex));
return false;
}
}
在上面的例子中是否有更好的方法來處理異常?
在此先感謝您的幫助。
克萊爾
除了Rob Stevenson-Leggetts的回答,我還會讓捕捉異常更具體。例如首先捕獲一個SqlException,因爲它將包含關於實際錯誤和堆棧跟蹤的更多特定信息。 讓catch(Exception ex)作爲最後的catch-block。 – 2010-08-10 10:02:04