我決定刪除我的代碼中的一些使用語句,所以我可以捕獲特定的異常並處理手動處理資源。我已經重構了一些代碼,使它更具可讀性和可維護性,在實現了新的try/catch塊之後,我仍然想知道它們是否已經正確地放置在手頭的任務上。異常處理的位置 - C#
例子:
public static DataTable Select(string table, string[] column, Object operand)
{
DataTable dTable = null;
SQLiteConnection connection = null;
SQLiteCommand command = null;
SQLiteDataReader dReader = null;
//convert to array for arguments
StringBuilder query = new StringBuilder();
query.Append("select ");
for (int i = 0; i < column.Length; i++)
{
query.Append(column[i]);
if (i < column.Length - 1)
{
query.Append(",");
}
}
query.Append(" from ");
query.Append(table);
try
{
connection = new SQLiteConnection(_connectionString);
command = new SQLiteCommand(query.ToString(), connection);
dTable = new DataTable();
connection.Open();
dReader = command.ExecuteReader();
dTable.Load(dReader);
return dTable;
}
catch (SQLiteException sqle)
{
//Handle exception
}
finally
{
connection.Dispose();
command.Dispose();
dReader.Dispose();
dTable.Dispose();
}
return null;
}
在這個例子中,我只實現的try/catch周圍的SQL操作本身,我這樣做是因爲它確保了被拋出可以注意到和資源配置的任何異常正確。然後我注意到這會讓for循環打開異常,儘管提供的索引器將通過GUI進行保護和創建。
我是明智的將整個方法封裝在try/catch語句中,還是我過於謹慎?當涉及到管理報表本身的位置時,您可以說我正在尋找最佳實踐。
謝謝你的時間!
編輯:
我知道using語句將是理想的處理處置和資源管理方面然而,由於在這個問題開頭提到我希望能夠捕獲特定類型的異常,特別是從SQLite組件生成的異常。
備註:您使用字符串連接來構建查詢,因此請小心這裏的SQL注入攻擊。在這種方法之外,傳遞給它的參數需要提前檢查問題可能並不明顯。直覺上,我期望數據訪問類來處理,但這不是。 – David 2011-04-03 20:37:11
我在所有方法中使用參數化查詢,列由GUI生成,不能通過用戶輸入手動輸入。感謝指針雖然:) – 2011-04-03 21:48:50