try-finally (référence C#)

Le bloc d' finally est utile pour nettoyer toutes les ressources allouées dans le bloc de test , et pour exécuter tout code qui doit s'exécuter même si une exception est levée dans le bloc d' try .En général, les instructions d'un bloc d' finally sont exécutées lorsque le contrôle permet une instruction d' try , si le transfert du contrôle se produit suite à l'exécution normale, de l'exécution d' break, d' continue, d' goto, ou de l'instruction d' return , ou de propagation d'une exception hors de l'instruction d' try .

Dans une exception gérée, le bloc associé d' finally est garantie.Toutefois, si l'exception est pas gérée, l'exécution du bloc d' finally dépend de la façon dont l'opération de déroulement d'exception est levée.Ce, à son tour, dépend de la façon dont votre ordinateur est configuré.Pour plus d'informations, consultez Unhandled Exception Processing in the CLR.

Généralement, lorsqu'une exception non gérée termine une application, si le bloc d' finally est exécuté n'est pas important.Toutefois, si vous avez des instructions d'un bloc d' finally qui doit être exécuté même dans ce cas, une solution consiste à ajouter un bloc d' catch à l'instruction d' try- d'finally .Sinon, vous pouvez intercepter l'exception qui peut être levée dans le bloc d' try d' try- partie supérieure d'instruction d'finally une supérieure la pile des appels.Autrement dit, vous pouvez intercepter l'exception de la méthode qui appelle la méthode qui contient l'instruction d' try- d'finally , ou dans la méthode qui appelle cette méthode, ou dans toute méthode dans la pile des appels.Si l'exception n'est pas interceptée, l'exécution du bloc d' finally varie selon que le système d'exploitation choisit de déclencher une opération de déroulement d'exception.

Exemple

Dans l'exemple suivant, une instruction non valide de conversion entraîne une exception d' System.InvalidCastException .L'exception n'est pas prise en charge.

public class ThrowTestA
{
    static void Main()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            Console.WriteLine("WriteLine at the end of the try block.");
        }
        finally
        {
            // To run the program in Visual Studio, type CTRL+F5. Then 
            // click Cancel in the error dialog.
            Console.WriteLine("\nExecution of the finally block after an unhandled\n" +
                "error depends on how the exception unwind operation is triggered.");
            Console.WriteLine("i = {0}", i);
        }
    }
    // Output:
    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
    //
    // Execution of the finally block after an unhandled
    // error depends on how the exception unwind operation is triggered.
    // i = 123
}

Dans l'exemple suivant, une exception de la méthode d' TryCast est interceptée dans une méthode situé plus haut de la pile des appels.

public class ThrowTestB
{
    static void Main()
    {
        try
        {
            // TryCast produces an unhandled exception.
            TryCast();
        }
        catch (Exception ex)
        {
            // Catch the exception that is unhandled in TryCast.
            Console.WriteLine
                ("Catching the {0} exception triggers the finally block.",
                ex.GetType());

            // Restore the original unhandled exception. You might not
            // know what exception to expect, or how to handle it, so pass 
            // it on.
            throw;
        }
    }

    public static void TryCast()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            Console.WriteLine("WriteLine at the end of the try block.");
        }
        finally
        {
            // Report that the finally block is run, and show that the value of
            // i has not been changed.
            Console.WriteLine("\nIn the finally block in TryCast, i = {0}.\n", i);
        }
    }
    // Output:
    // In the finally block in TryCast, i = 123.

    // Catching the System.InvalidCastException exception triggers the finally block.

    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
}

Pour plus d'informations sur finally, consultez l' essai-Catch-enfin.

C# contient également instruction using, qui fournissent une syntaxe pratique pour les mêmes fonctionnalités qu'une instruction d' try- d'finally .

Spécification du langage C#

Pour plus d'informations, consultez la Spécification du langage C#. La spécification du langage est la source de référence pour la syntaxe C# et son utilisation.

Voir aussi

Tâches

Comment : lever explicitement des exceptions

Référence

Mots clés C#

test, Catch, et instructions de jet (C++)

Instructions de gestion des exceptions (Référence C#)

throw (référence C#)

try-catch (référence C#)

Concepts

Guide de programmation C#

Autres ressources

Référence C#