3

最終的に使用することの違いは何ですか

void ReadFile(int index)
{
    // To run this code, substitute a valid path from your local machine
    string path = @"c:\users\public\test.txt";
    System.IO.StreamReader file = new System.IO.StreamReader(path);
    char[] buffer = new char[10];
    try
    {
        file.ReadBlock(buffer, index, buffer.Length);
    }
    catch (System.IO.IOException e)
    {
        Console.WriteLine("Error reading from {0}. 
           Message = {1}", path, e.Message);
    }
    finally
    {
        if (file != null)
        {
            file.Close();
        }
    }
    // Do something with buffer...
}

そしてそれを使用していませんか?

void ReadFile(int index)
{
    // To run this code, substitute a valid path from your local machine
    string path = @"c:\users\public\test.txt";
    System.IO.StreamReader file = new System.IO.StreamReader(path);
    char[] buffer = new char[10];
    try
    {
        file.ReadBlock(buffer, index, buffer.Length);
    }
    catch (System.IO.IOException e)
    {
        Console.WriteLine("Error reading from {0}. 
            Message = {1}", path, e.Message);
    }

    if (file != null)
    {
        file.Close();
    }

    // Do something with buffer...
}
4

4 に答える 4

6

前者の例はfile.Close()、例外がスローされたかどうか、またはどの例外がスローされたかに関係なく実行されます。

後者は、例外がスローされない場合、またはaSystem.IO.IOExceptionがスローされた場合にのみ実行されます。

于 2010-12-23T14:29:44.957 に答える
3

違いは、使用せずにスローされfinallyた以外の例外が発生した場合、行に到達しないIOExceptionため、アプリケーションがファイルハンドルをリークすることです。.Close

個人的には、ストリームなどの使い捨てリソースを処理するときは、常にブロックを使用します。

try
{
    using (var reader = File.OpenText(@"c:\users\public\test.txt"))
    {
        char[] buffer = new char[10];
        reader.ReadBlock(buffer, index, buffer.Length);
         // Do something with buffer...
    }
}
catch (IOException ex)
{
    Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}

このように、私はそれらを適切に処分することを心配する必要はありません。try / finalはコンパイラーによって処理され、ロジックに集中できます。

于 2010-12-23T14:29:33.660 に答える
1

catchブロック自体が例外をスローする場合があります(pathがnull参照の場合の状況を考慮してください)。tryまたは、ブロックでスローされた例外System.IO.IOExceptionは処理されないため、処理されません。どちらの場合も、使用しない限りファイルハンドルは閉じられませんfinally

于 2010-12-23T14:33:44.883 に答える
0

あなたの場合、何もありません。例外をcatchブロックからスローさせると、finally部分は実行されますが、他のバリエーションは実行されません。

于 2010-12-23T14:29:38.763 に答える