1

如果我有很多异常要处理,那么 C# 异常处理的最佳方法是什么?

我会将它们全部放在 try 块中还是尽可能多地放入 try 块?

例如,当我按如下方式连接到数据库时,

放置 try...catch...finally 块的最佳方法是什么?

OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=school.mdb");
conn.Open();
string sql = "select * from sheet1 where student='stu2'";
OleDbCommand command;
command = new OleDbCommand(sql, conn);
OleDbDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    for (int i = 0; i < reader.FieldCount; i++)
    {
        Console.Write("{0} ", reader[i]);
    }

    Console.WriteLine();
}

reader.Close();
conn.Close();
4

1 回答 1

1

一个小小的异常处理提示:如果抛出异常,您的代码不会自行清理。无论是否引发异常,以下代码都将清理:

using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=school.mdb"))
{
    conn.Open();
    string sql = "select * from sheet1 where student='stu2'";
    using (OleDbCommand command = new OleDbCommand(sql, conn))
    {
        using (OleDbDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    Console.Write("{0} ", reader[i]);
                }

                Console.WriteLine();
            }
        }
    }
    conn.Close();
}
于 2013-01-23T03:05:22.643 回答