Does the point of trying to catch finally block?

What is the difference between using finally

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...
}

and not use it?

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...
}
+3
source share
4 answers

In the first example, it will be executed file.Close()regardless of whether an exception is selected or which exception is selected.

The latter will only work if no exception is thrown or if thrown System.IO.IOException.

+7
source

The difference is that if you are not using finallyand you get an exception other than IOExceptionyour application will leak the file descriptor because the line .Closewill never be reached.

, :

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/finally , .

+3

catch ( , path ). , try System.IO.IOException, . , finally.

+1

. catch, , .

0

Source: https://habr.com/ru/post/1781845/


All Articles