Expression.TryCatchFinally(Expression, Expression, CatchBlock[]) Method

Definition

Creates a TryExpression representing a try block with any number of catch statements and a finally block.

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

Parameters

body
Expression

The body of the try block.

finally
Expression

The body of the finally block.

handlers
CatchBlock[]

The array of zero or more CatchBlock expressions representing the catch statements to be associated with the try block.

Returns

The created TryExpression.

Examples

The following example demonstrates how to create a TryExpression object that contains a catch statement and a finally statement.

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

// A TryExpression object that has a catch statement and a finally statement.
// The return types of the try block and all catch blocks must be the same.
TryExpression tryCatchExpr =
    Expression.TryCatchFinally(
        Expression.Block(
            Expression.Throw(Expression.Constant(new DivideByZeroException())),
            Expression.Constant("Try block")
        ),
        Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("Finally 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:
//
// Finally block
// Catch block

Applies to

Product 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, 10
.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