[フレーム]

Throwing Exceptions In Expressions In C# 7.0

C# version 7.0 introduced a new feature or we can say more flexible to throw the exceptions in Lambda expressions. Before seeing this, we know what we can do earlier in C# 6.0.

Earlier up to C# 6.0, If you want to throw an exception we need to create a separate method and call that in respective expressions as follows,

  1. publicvoid ThrowingExceptionsInExpressionsOld()
  2. {
  3. string obj = null;
  4. string noException = obj ? ? RaiseException();
  5. }
  6. public string RaiseException()
  7. {
  8. thrownew Exception("Object is null");
  9. }

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 don't need to implement any additional method to raise an exception as above, instead, we can use direct throw statement in the expression. Following is the simplified code in C# 7.0.

  1. publicvoid ThrowingExceptionsInExpressions()
  2. {
  3. string obj = null;
  4. string noException = obj ? ?
  5. thrownew Exception("Object is null");
  6. }

The same way we can have a throw exceptions in Expression Bodied Constructors, Finalizers and Properties as well as while using conditional operators as shown below.

  1. string[] names = {};
  2. string firstName = names.Length > 0 ? names[0] : thrownew ApplicationException("Cannot set a default name");

As these changes doesn't effect much at runtime, but these features will improve readability and also simplifies the development.

You can see complete code here in GitHub.

Happy Coding :)

Learn more about Exception Handling in C#
People also reading
Membership not found

AltStyle によって変換されたページ (->オリジナル) /