Share via


Tente catch de--finalmente (referência de C#)

Um uso comum de catch e finally juntos é obter e usar recursos em um try Bloquear, lidar com circunstâncias excepcionais em um catch Bloquear e liberar os recursos a finally bloco.

Para obter mais informações e exemplos sobre relançar exceções, consulte try-catch e Lançando exceções.

Exemplo

public class EHClass
{
    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...
    }

}

Especificação da linguagem C#

Para obter mais informações, consulte C# Language Specification A especificação de linguagem é a fonte definitiva para a sintaxe e o uso de C#.

Consulte também

Tarefas

Como: Lançar exceções explicitamente

Referência

C# Keywords

The try, catch, and throw Statements

Exception Handling Statements (C# Reference)

throw (C# Reference)

usando instrução (referência de C#)

Conceitos

C# Programming Guide

Outros recursos

C# Reference