尝试抓点终于阻止?

bev*_*qua 3 c# try-catch try-catch-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...
}
Run Code Online (Sandbox Code Playgroud)

而不是使用它?

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...
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*wns 7

file.Close()无论是抛出异常还是抛出异常,前一个示例都将运行.

后者只有在没有抛出异常或System.IO.IOException抛出a时才会运行.