处理异常的最佳方法,需要处理很多异常

时间:2013-01-23 02:56:36

标签: c# exception-handling

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

我会把所有这些都放在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();

1 个答案:

答案 0 :(得分: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();
}