While exceptions have always existed in C# the throw
keyword was only treated as a statement which meant it could not be used in places where only expressions were allowed such as inside a conditional or coalescing operator.
C# 7.0 introduces throw expressions which allow exceptions to be thrown in more convenient ways.
Code
C#
void ProcessAdult(string name, age)
{
var requiredName = name ?? throw new ArgumentNullException(nameof(name));
var adultAge = age >= 18 ? age : throw new ArgumentOutOfRangeException(nameof(age));
// ...
}
C#
void ProcessAdult(string name, age)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var requiredName = name;
if (age < 18)
{
throw new ArgumentOutOfRangeException(nameof(age));
}
var adultAge = age;
// ...
}