Using throw-expressions in C#
gpeipman
7,314 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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()
{
References
- C# 7.0: Throw expressions (Gunnar Peipman)
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.