Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#

What are throw expressions in C#?

Hammad Nasir

Overview

In the versions prior to C# 7.0, throw was a statement and therefore couldn’t be used in certain places. These places included:

  • Conditional expressions
  • Null coalescing expressions
  • Some lambda expressions

However, with the introduction of throw expressions, this restriction has been lifted.

Examples

The following code shows how throw expressions can be used inside conditional expressions:

class Program {
  private static int[] arr;

  static void Main() {
    arr = new int[5];
    
    for (int i = 0; i < 5; i++) {
      arr[i] = i + 1;
    }

    System.Console.WriteLine(getValue(5)); // Error is thrown here
  }

  private static int getValue(int index) {
    return index < arr.Length ? arr[index] :
            throw new System.IndexOutOfRangeException("Index specified is out of bounds of the array");
  }
}

In the example above, a static integer array member, arr, is declared inside the Program class.

arr is initialized with an integer array of size 5 and is filled with 1 2 3 4 5 elements respectively inside the Main method.

Afterward, the getValue method is invoked with index 5 (which is out of bounds). The getValue function returns the value at the specified index if the index is in bounds.

If it is not (which is the case here), an IndexOutOfRangeException error is thrown. Notice that this error is thrown inside a conditional expression.

The following code shows how throw expressions can be used inside null coalescing expressions:

class Program {
  private static int x;

  public static int X {
    get => x;
    set => x = value ??
            throw new ArgumentNullException(paramName: nameof(value), message: "X cannot be null");
  }
  
  static void Main() {
    X = null; // Error is thrown here
  }
}

In the example above, an integer member x has a corresponding property X with getters and setters defined. In the set method, the null coalescing operator (??) checks whether the value is null or not.

If it is null, then ArgumentNullException is thrown. Since we try to set X equals to null in the Main method, this error will be thrown. Notice that this error is thrown inside a null coalescing expression.

The following code shows how throw expressions can be used inside lambda functions:

class Program {
  static void Main() {
    throwException();
  }

  private static int throwException => 
          throw new System.IndexOutOfRangeException();
}

In the example above, we make a lambda function throwException, which only throws IndexOutOfRangeException and does nothing else.

RELATED TAGS

c#

CONTRIBUTOR

Hammad Nasir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring