我决定删除我的代码中的一些使用语句,所以我可以捕获特定的异常并处理手动处理资源。我已经重构了一些代码,使它更具可读性和可维护性,在实现了新的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