Back to: C#.NET Tutorials For Beginners and Professionals
Thrown Expression in C# 7 with Examples
In this article, I am going to discuss the Thrown Expression in C# 7 with Examples. Please read our previous article before proceeding to this article where we discussed the Expression Bodied Members in C# 7 with Examples. In C#, it is very easy to throw an exception in the middle of an expression.
Example to Understand Thrown Expression in C#
Let us understand Thrown Expression in C# with an example. Please have a look at the below example. The following example code is self-explained, so please go throw the comments line for a better understanding. As you can see in the below code, within the Divide method, we are throwing an exception when the SecondNumber value is 0. That is throwing an exception in the middle of the program execution.
using System; namespace ThrownExpressionDemo { class Program { static void Main(string[] args) { Console.WriteLine("Main Method Execution Started..."); //Calling the Divide Method by passing 10 and 0 var Result = Divide(10, 0); Console.WriteLine($"Result: {Result}"); Console.WriteLine("Main Method Execution Completed..."); Console.ReadKey(); } public static double Divide(int FirstNumber, int SecondNumber) { //Throwing an Exception in the Middle of the Program Exceution if (SecondNumber == 0) { //As the Second Number is 0, throwing a Exception throw new DivideByZeroException(); } else { return FirstNumber % SecondNumber; } } } }
In the above example, we are throwing an expression in the middle of the method execution 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 as follows to throw an exception in the middle of the expression.
using System; namespace ThrownExpressionDemo { class Program { static void Main(string[] args) { Console.WriteLine("Main Method Execution Started..."); //Calling the Divide Method by passing 10 and 0 var Result = Divide(10, 0); Console.WriteLine($"Result: {Result}"); Console.WriteLine("Main Method Execution Completed..."); Console.ReadKey(); } public static double Divide(int FirstNumber, int SecondNumber) { //Throwing an Exception in the Middle of the Expression return SecondNumber != 0 ? FirstNumber % SecondNumber : throw new DivideByZeroException(); } } }
When you run the above code, you will get the following Runtime Exception.
You can throw any type of exception in the middle of an expression like IndexOutOfRangeException, NullReferenceException, OutOfMemoryException, StackOverflowException, and many other types of exceptions.
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 Real-Time Example:
The below example uses a simple Employee class to demonstrate different situations where we can throw an exception in an expression. They are as follows
- Auto-Property Initializer Statement
- Inline Comparison using the “?” operator
- Expression-Bodied Member
For a better understanding, please have a look at the below example.
using System; namespace ThrownExpressionDemo { 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); } } } 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"); } }
Output:
In the next article, I am going to discuss the Async Main Method in C# 7 with Examples. Here, in this article, I try to explain Thrown Expression in C# 7 with Examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.