Back
Close

Using throw-expressions in C#

gpeipman
1,749 views

Using throw-expressions in C# 7.0

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

This example uses simple Person class to demonstrate different situations where throw-expressions can be used:

  • auto-property initializer statement
  • inline comparison using operator "?"
  • expression-bodied member

Check the output of demo under code window after running it.

Click Run to see demo
·using System;
namespace CS7
{
class Person
{
public string Name { get; }
public Person(string name) => Name = name ?? throw new ArgumentNullException(name);
public string GetFirstName()
{
var parts = Name.Split(' ');
return (parts.Length > 1) ? parts[0] : throw new InvalidOperationException("No full name.");
}
public string GetLastName() => throw new NotImplementedException();
}
class Program
{
static void Main(string[] args)
{
TryWithNameNull();
TryGetFirstName();
TryGetLastName();
}
static void TryWithNameNull()
{
try
{
new Person(null);
}
catch(Exception ex)
{
Console.WriteLine(ex.GetType() + ": " + ex.Message);
}
}
static void TryGetFirstName()
{
try
{
new Person("Gunnar").GetFirstName();
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType() + ": " + ex.Message);
}
}
static void TryGetLastName()
{
try
{
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

References

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants