Throwing Exceptions in Expressions: C# 7.0
In C# 7.0, they introduced a new feature or we can say more flexible to throw the exceptions in Lambda expressions. Before seeing this, yet we know what we will do earlier in C# 6.0.
Earlier up to C# 6.0, If you what to throw an exception we need to create a separate method and call that in respective Expressions as follows
public void ThrowingExceptionsInExpressionsOld() { string obj = null; string noException = obj ?? RaiseException(); } public string RaiseException() { throw new Exception("Object is null"); }
In the above code, we are trying to raise an exception via a new method in null coalescing expression. Now, from C# 7.0, we no need to implement any additional method to raise an exception as above, instead, we can use a direct throw statement in the expression. Following is the simplified code of above in C# 7.0.
public void ThrowingExceptionsInExpressions() { string obj = null; string noException = obj ?? throw new Exception("Object is null"); }
The same way we can even have a throw exception in Expression Bodied Constructors, Finalizers and Properties as well as while using conditional operators as shown below.
string[] names = {}; string firstName = names.Length > 0 ? names[0] : throw new ApplicationException("Cannot set a default name");
As these changes don’t affect much at runtime, but these features will improve readability and also simplifies the development.
You can see complete code here in GitHub
Happy Coding 🙂