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

One little exception-handling hint: your code is not cleaning up after itself in case an exception is thrown. The following code will clean up, whether or not an exception is thrown:

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 に答える