Expression.TryCatch(Expression, CatchBlock[]) Méthode

Définition

Crée un TryExpression qui représente un bloc Try avec un nombre quelconque d'instructions Catch mais ni une erreur, ni un bloc Finally.

C#
public static System.Linq.Expressions.TryExpression TryCatch (System.Linq.Expressions.Expression body, params System.Linq.Expressions.CatchBlock[] handlers);
C#
public static System.Linq.Expressions.TryExpression TryCatch (System.Linq.Expressions.Expression body, params System.Linq.Expressions.CatchBlock[]? handlers);

Paramètres

body
Expression

Corps du bloc Try.

handlers
CatchBlock[]

Tableau de zéro ou plusieurs expressions CatchBlock qui représente les instructions Catch à associer au bloc Try.

Retours

Élément TryExpression créé.

Exemples

L’exemple suivant montre comment créer un TryExpression objet qui contient une instruction catch.

C#
// Add the following directive to the file:
// using System.Linq.Expressions;

// A TryExpression object that has a Catch statement.
// The return types of the Try block and all Catch blocks must be the same.
TryExpression tryCatchExpr =
    Expression.TryCatch(
        Expression.Block(
            Expression.Throw(Expression.Constant(new DivideByZeroException())),
            Expression.Constant("Try block")
        ),
        Expression.Catch(
            typeof(DivideByZeroException),
            Expression.Constant("Catch block")
        )
    );

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
// If the exception is caught,
// the result of the TryExpression is the last statement
// of the corresponding Catch statement.
Console.WriteLine(Expression.Lambda<Func<string>>(tryCatchExpr).Compile()());

// This code example produces the following output:
//
// Catch block

S’applique à

Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0