Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A throw expression in C# allows the throw keyword to be evaluated as an expression rather than a standalone statement. Introduced in C# 7.0, this feature enables developers to raise exceptions inline within specific expression contexts where a value is expected. Because a thrown exception unconditionally terminates the current execution path, a throw expression has no resulting value. Instead, the C# language specification dictates that a throw expression has an implicit conversion to any type. This satisfies the compiler’s definite assignment and return type requirements within the expression tree.

Syntactic Contexts

The C# language specification strictly limits throw expressions to specific grammatical contexts. You cannot use a throw expression arbitrarily in any place an expression is expected (such as a method argument or a standard binary operation). It is permitted exclusively in the following constructs: 1. The Null-Coalescing Operator (??) The throw expression can serve as the right-hand operand of a null-coalescing operation. If the left-hand operand evaluates to null, the expression evaluates the right-hand operand, throwing the exception.
string? input = null;
string value = input ?? throw new ArgumentNullException(nameof(input));
2. The Conditional (Ternary) Operator (?:) A throw expression can be used as either the consequence (true) or alternative (false) branch of a conditional operator. The compiler infers the type of the entire ternary expression from the non-throwing branch.
int age = -5;
int validAge = age >= 0 ? age : throw new ArgumentOutOfRangeException(nameof(age));
3. Expression-Bodied Members and Functions (=>) Methods, properties, indexers, and constructors defined using expression-bodied syntax can consist entirely of a throw expression. Additionally, throw expressions can serve as the body for anonymous functions (lambdas) and local functions.
using System;

public class Entity
{
    // Expression-bodied property
    public string Name => throw new NotImplementedException();

    // Expression-bodied method
    public int GetId() => throw new NotSupportedException();

    public void Evaluate()
    {
        // Lambda expression
        Func<int> getInt = () => throw new InvalidOperationException();

        // Local function
        void LocalFunc() => throw new Exception();
    }
}
4. Switch Expressions Introduced in C# 8.0, switch expressions allow throw expressions within their switch arms. This is typically used in conjunction with the discard pattern (_) to handle non-exhaustive matches.
using System;

int state = 3;
string stateName = state switch
{
    0 => "Idle",
    1 => "Active",
    _ => throw new ArgumentException("Invalid state", nameof(state))
};

Compiler Evaluation Mechanics

When the C# compiler encounters a throw expression, it does not bypass type-checking. Instead, the C# specification explicitly defines that a throw expression possesses an implicit conversion to every type. Because the evaluation of a throw expression never successfully yields a value to the surrounding execution context (it is a non-returning operation), the type-checker actively applies this universal implicit conversion rule to satisfy the expression tree’s requirements. For example, in the ternary operation age >= 0 ? age : throw new ArgumentOutOfRangeException(), the compiler evaluates the true branch as type System.Int32. It evaluates the false branch as a throw expression. The type-checker then applies the implicit conversion from the throw expression to System.Int32, safely resolving the type of the entire ternary expression as System.Int32 without generating a type mismatch error.
Master C# with Deep Grasping Methodology!Learn More