Expression.Throw Method

Definition

Creates a UnaryExpression that represents a throwing of an exception.

Overloads

Throw(Expression)

Creates a UnaryExpression that represents a throwing of an exception.

Throw(Expression, Type)

Creates a UnaryExpression that represents a throwing of an exception with a given type.

Throw(Expression)

Source:
UnaryExpression.cs
Source:
UnaryExpression.cs
Source:
UnaryExpression.cs

Creates a UnaryExpression that represents a throwing of an exception.

C#
public static System.Linq.Expressions.UnaryExpression Throw(System.Linq.Expressions.Expression value);
C#
public static System.Linq.Expressions.UnaryExpression Throw(System.Linq.Expressions.Expression? value);

Parameters

Returns

A UnaryExpression that represents the exception.

Examples

The following example demonstrates how to create a TryExpression object that uses the Throw method.

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

Applies to

.NET 10 and other versions
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

Throw(Expression, Type)

Source:
UnaryExpression.cs
Source:
UnaryExpression.cs
Source:
UnaryExpression.cs

Creates a UnaryExpression that represents a throwing of an exception with a given type.

C#
public static System.Linq.Expressions.UnaryExpression Throw(System.Linq.Expressions.Expression value, Type type);
C#
public static System.Linq.Expressions.UnaryExpression Throw(System.Linq.Expressions.Expression? value, Type type);

Parameters

type
Type

The new Type of the expression.

Returns

A UnaryExpression that represents the exception.

Applies to

.NET 10 and other versions
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