An unexpected runtime error arises in the code when an application or system constraint is being violated by the program, for example, when a program is dividing a number by zero, trying to connect to a non-existing database, or trying to open an XML file which is corrupted. We need a block of code to catch these exceptions.

Throw Expressions in C# 7.0

C# 7 introduces a new feature called Throw Expressions, which will allow us to throw exceptions from conditional expressions, null-coalescing expressions, and most importantly, with expression-bodied members. Throw expressions will let you write a short and precise code which will hasten performance of the code. Before C# 7, throw was just a statement, but now it can be used within the body of the code because it now works as an expression. Let’s see, where and how we can use throw expressions.

Previously, there were only two options to throw an exception within an expression:

            var dayString = "monday,tuesday, friday".Split(",");
            var days = (dayString.Length > 0) ? dayString : null;
            if (days == null)
            {
                throw new Exception("There are no days");
            }

Or this:

            var dayString = "monday,tuesday, friday".Split(",");
            var days = (dayString.Length > 0) ? dayString : null;
            if (days == null)
            {
                throw new Exception();
            }

Conditional Expressions

You can now throw an exception in the middle of expression in the conditional operators. For example:

            string[] Days;
            var arrayFirstDay = Days.Length > 0 ? Days[1] : throw new  Exception("Array is empty");

Null Coalescing Expressions

It is now possible to throw an exception as the second condition without checking for null in the Null Coalescing operator. For example:

 var strName = name ?? throw new ArgumentException();

Expression-Bodied Members

Even before C# 6, it was not possible to write a method using a single statement. C# 6 has solved this problem by adding a fat arrow “=>” in it. Consider this example:

        public string GetNumber()
        {
            return "1234";
        }

The above code can be written like this in C# 6:

        public string GetNumber() => "1234";

As throwing an expression was not allowed by the compiler in C# 6, there were limited options to complete the method in Expression-Bodied Members. Either there was no indication of program functioning properly, or you have to first convert the expression to a standard function to throw the exception. In C# 7, you can easily throw an exception within Expression-Bodied Members. Like this:

public string GetNumber() => throw new NotImplementedException();

Simpler Constructors

Constructors are important when making classes, and we can’t create objects in classes which are in invalid state. To get rid of this problem, we introduce validations in constructors. The most important validation is to check if the object passed to the constructor is not null. Before the introduction of throw expressions in C# 7, this code was really cumbersome:

        public void StartService
            (string serviceName, string ServiceLocation)
        {
            string MyserviceName, MyServiceLocation;

            if (serviceName == null)
            {
                throw new ArgumentNullException(nameof(serviceName));
            }

            if (ServiceLocation == null)
            {
                throw new ArgumentNullException(nameof(ServiceLocation));
            }
            MyserviceName = serviceName;
            MyServiceLocation = ServiceLocation;

        }

Here you have to write lots of curly braces and the code looks never-ending. This can be simplified with a clean looking code for writing a constructor in C# 7 using throw expressions like this:

        public void StartService
            (string serviceName, string ServiceLocation)
        {
            string MyserviceName, MyServiceLocation;
            MyserviceName = serviceName ?? throw new ArgumentNullException(nameof(serviceName));
            MyServiceLocation = ServiceLocation ?? throw new ArgumentNullException(nameof(ServiceLocation));
        }

Short Setters

You can now make your property setters terser with throw expressions. Consider this example:

        string _service;
        public string Service
        {
            set
            {
                if (value == null)
                {
                    throw new ArgumentException();
                }
                _service = value;
            }
        }

In C# 7 using throw expressions, it can be written as:

        public string Service
        {
            set
            {
                _service = value ?? throw new ArgumentException();
            }
        }

Or can be even simplified in just one expression together with the expression body:

        string _service;
        public string Service
        {
            set => _service = value ?? throw new ArgumentException();

        }

Hence, now with throw expressions in C# 7, your code will look terser yet expressive. You don’t have to write lines and lines of codes.

Related Articles

Create a Simple Thread Program Using C#

Objects and Classes in C#

C# Do while loop

Last modified: March 6, 2019

Comments

Write a Reply or Comment

Your email address will not be published.