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

En utilisant un bloc finally, vous pouvez nettoyer toutes les ressources qui sont allouées dans un bloc try, et vous pouvez exécuter le code même si une exception est levée dans le bloc try. En général, les instructions d'un bloc finally s'exécutent quand le contrôle quitte une instruction try. Le transfert du contrôle peut se produire suite à une exécution normale, à l'exécution d'une instruction break, continue, goto ou return, ou à la propagation d'une exception lors de l'instruction try.

Dans une exception gérée, l'exécution du bloc associé finally est garantie. Toutefois, si l'exception n'est pas gérée, l'exécution du bloc finally dépend de la façon dont l'opération de déroulement d'exception est levée. Cela dépend ensuite de la façon dont votre ordinateur est configuré. Pour plus d'informations, consultez Traitement d'exceptions non gérées dans le CLR.

Généralement, lorsqu'une exception non gérée termine une application, peu importe que le bloc finally soit en cours d'exécution ou pas. Toutefois, si vous avez des instructions dans un bloc finally qui doivent être exécutées même dans ce cas, la solution consiste à ajouter un bloc catch à l'instruction try-finally. Vous pouvez aussi intercepter l'exception qui peut être levée dans le bloc try d'une instruction try-finally plus haut dans la pile des appels. En d'autres termes, vous pouvez intercepter l'exception dans la méthode qui appelle la méthode contenant l'instruction try-finally, ou dans la méthode qui appelle cette méthode, ou dans n'importe quelle méthode de la pile des appels. Si l'exception n'est pas interceptée, l'exécution du bloc 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 de conversion non valide entraîne la levée d'une exception System.InvalidCastException. L'exception est non gérée.

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 TryCast est interceptée dans une méthode située plus haut dans 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 try-catch-finally.

C# contient également l'instruction Using, qui fournit des fonctionnalités similaires pour les objets IDisposable dans une syntaxe pratique.

Spécification du langage C#

Pour plus d'informations, voir 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#

Instructions try, throw et catch (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#