异常处理放置 - C#

Jam*_*ing 3 c# exception-handling try-catch-finally

我决定删除代码中的一些using语句,这样我就可以捕获特定的异常并手动处理资源.我已经重构了一些代码,使其更具可读性和maintable,执行新的try/catch块,如果他们已经被正确地放置在手头的任务,我在想后.

例:

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;
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我只在SQL操作本身周围实现了try/catch,我这样做是因为它确保可以注意到抛出的任何异常并且资源被正确处理.然后我注意到这使得for循环对异常开放,尽管提供的索引器将受到保护并通过GUI创建.

我是否明智地将整个方法封装在try/catch语句中或者我是否过于谨慎?你可以说我正在寻找管理语句本身位置的最佳实践.

谢谢你的时间!

编辑:

我知道using语句在处理资源的处理和管理方面是理想的,但正如问题开头所提到的,我希望能够捕获特定类型的异常,特别是那些从SQLite组件生成的异常.

Jan*_*Jan 9

不要忘记null检查:

finally {
  if (connection != null) connection.Dispose();
  if (command != null) command.Dispose();
  if (dReader != null) dReader.Dispose();
  if (dTable != null) dTable.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

其中一个构造函数可能会抛出异常,在这种情况下,对象将不会被初始化.