Thrown Expression in C#

Thrown Expression in C# 7 with examples

In this article, I am going to discuss the Thrown Expression in C# with some examples. Please read our previous article before proceeding to this article where we discussed the Expression Bodied Members in C# with examples. In C#, it is very easy to throw an exception in the middle of an expression.

Let us understand Thrown Expression in C# with an example.

class Program
{
    static void Main(string[] args)
    {
        var a = Divide(10, 0);

        Console.WriteLine("Press any key to exist.");
        Console.ReadKey();
    }
    public static double Divide(int x, int y)
    {
        if (y == 0)
        {
            throw new DivideByZeroException();
        }
        else
        {
            return x % y;
        }
    }
}

In the above example, we are throwing an expression in the middle of the method by checking the condition. But with C# 7.0 now it is possible to throw an exception in the middle of an expression. Let’s rewrite the above program to throw an exception in the middle of the expression as shown below.

class Program
{
    static void Main(string[] args)
    {
        var a = Divide(10, 0);

        Console.WriteLine("Press any key to exist.");
        Console.ReadKey();
    }
    public static double Divide(int x, int y)
    {
        return y != 0 ? x % y : throw new DivideByZeroException();
    }
}
OUTPUT:

Thrown Expression in C#

You can throw any type of exception in the middle of an expression like “IndexOutOfRangeException”, “NullReferenceException”, “OutOfMemoryException”, “StackOverflowException” and many other types of exception.

You can add exception throwing to expression-bodied members, null-coalescing expressions, and conditional expressions. Throw expressions are the way to tell the compiler to throw the exception under specific conditions like in expression bodied members or inline comparisons.

Thrown Expression in C# real-time example:

This below example uses a simple Employee class to demonstrate different situations where throw expression in C# can be used:

  1. auto-property initializer statement
  2. inline comparison using the operator “?”
  3. expression-bodied member
class Employee
{
    public string FullName { get; }
    public Employee(string name) => FullName = name ?? throw new ArgumentNullException(name);
    public string GetFirstName()
    {
        var parts = FullName.Split(' ');
        return (parts.Length > 1) ? parts[0] : throw new InvalidOperationException("Method:GetFirstName, Full Name is not available");
    }
    public string GetLastName() => throw new NotImplementedException("Method GetLastName is not Implemented");
}

class Program
{
    static void Main(string[] args)
    {
        TryWithNameNull();
        TryGetFirstName();
        TryGetLastName();

        Console.WriteLine("Press any key to exist.");
        Console.ReadKey();
    }

    static void TryWithNameNull()
    {
        try
        {
            new Employee(null);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.GetType() + ": " + ex.Message);
        }
    }

    static void TryGetFirstName()
    {
        try
        {
            new Employee("Pranaya").GetFirstName();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.GetType() + ": " + ex.Message);
        }
    }

    static void TryGetLastName()
    {
        try
        {
            new Employee("Pranaya").GetLastName();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.GetType() + ": " + ex.Message);
        }
    }
}

OUTPUT:

Thrown Expression in C#

In the next article, I am going to discuss the Async Main in C# with some examples.

SUMMARY

In this article, I try to explain Thrown Expression in C# step by step with some simple examples. I hope this Thrown Expression in C# article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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