Throwing exceptions in expressions in C# 7.0
January 15, 2018 Leave a comment
C# 7.0 makes it possible to throw exceptions with ternary and null-coalescing operators.
Here’s an example where we throw an exception if the divisor is 0:
private double Divide(double what, double withWhat) { return withWhat != 0 ? what / withWhat : throw new ArgumentException("nono"); }
If the divisor is not 0 then we return the result otherwise we throw an exception.
Another place where we now can throw exceptions is with null-coalescing operators. Here’s a Dog class with a constructor where we want to throw an exception if the Dog name is null:
public class Dog { private string name; public Dog(string name) => this.name = name ?? throw new ArgumentNullException("Dog name"); }
View all various C# language feature related posts here.