Directly throw Exception as an Expression – Throw expressions in C# 7.0

By | July 31, 2017

In one of our previous post, Expression – Bodied Members in C# 7.0 , we have seen how C# 7.0 extended the expression bodied members features for several new members including  constructor, destructor, property assessors etc. C# 7.0 also introduces throw expressions, using which you can now throw an exception along with expression-bodied members, conditional expressions or even null-coalescing operations. Let’s have a look how it works.

Throw expressions are the simplified ways to raise the exceptions, where you just need to throw it, based on the condition. Consider the same example that we used in the previous post Expression – Bodied Members in C# 7.0

class Student
{
private string studentName;

// Expression – Bodied Constructor
public Student(string name) => studentName = name;
}

Now, in case you need to raise the exception here with the expression bodied method, you can take the following approach.

class Student
{
private string studentName;

// Expression – Bodied Constructor -- Throw Exception

public Student(string name) => studentName = name ?? throw new ArgumentNullException();

}

Similar, this works with Properties as well.

public string Name
{
get => studentName;
set => studentName = value;
}

In case you want to raise an exception while assign the value, you can simply do the following.

// Expression - Properties - Throw Exception
public string Name
{
get => studentName;
set => studentName = value ?? throw new ArgumentNullException();
}

All in all, Throw expressions  helps you to write smaller code block and using same patterns of expression to raise the exception, internally, it works in a same way.

ExceptionHope this helps

4 thoughts on “Directly throw Exception as an Expression – Throw expressions in C# 7.0

  1. Pingback: Dew Drop - July 31, 2017 (#2531) - Morning Dew

  2. Pingback: Declare Out variable right at the point – Out variable in C# 7.0

  3. Pingback: The week in .NET – Nuke, Warden.NET, .NET in Bangalore, and links! | .NET Blog

  4. Pingback: Improve Code readability using Digit Separator in C# 7.0

Leave a Reply

Your email address will not be published. Required fields are marked *