-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathExceptionProgram.cs
More file actions
107 lines (96 loc) · 3.06 KB
/
Copy pathExceptionProgram.cs
File metadata and controls
107 lines (96 loc) · 3.06 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
namespace Otus.AsyncAwait
{
public class ExceptionProgram
{
public async Task Execute1Async()
{
Task task = null;
try
{
task = ThrowInAsync(1);
await task;
}
catch (Exception e)
{
Console.WriteLine($"Exception Message: {e.Message}");
Console.WriteLine($"Exception Type: {task.Status}");
Console.WriteLine($"Exception Type: {task.IsFaulted}");
}
}
public async Task Execute2Async()
{
Task allTasks = Task.CompletedTask;
try
{
var task1 = ThrowInAsync(1);
var task2 = ThrowInAsync(2);
var task3 = ThrowInAsync(3);
Console.WriteLine("getting all tasks");
allTasks = Task.WhenAll(task1, task2, task3);
Console.WriteLine("after awaiting");
await allTasks;
}
catch (Exception e)
{
Console.WriteLine($"Exception Message: {e.Message}");
Console.WriteLine($"Exception Type: {e.GetType()}");
Console.WriteLine($"Is Faulted: {allTasks.IsFaulted}");
if (allTasks.Exception is not null)
{
foreach (var taskException in allTasks.Exception?.InnerExceptions)
{
Console.WriteLine($"Exception Message: {taskException.Message}");
}
}
}
}
public async Task Execute3Async()
{
Task<bool> task = null;
try
{
task = Task.Run<bool>(async () =>
{
await ThrowInAsync(1);
return true;
});
//var result = task.Result;
//task.Wait();
var result = task.GetAwaiter().GetResult();
}
catch (AggregateException e)
{
}
catch (Exception e)
{
Console.WriteLine($"Exception Message: {e.Message}");
Console.WriteLine($"Exception Type: {task.Status}");
Console.WriteLine($"Exception Type: {task.IsFaulted}");
}
}
public async Task Execute4Async()
{
try
{
MethodAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private async Task ThrowInAsync(int i)
{
//await Task.Delay(TimeSpan.FromMilliseconds(1));
throw new InvalidOperationException($"The task {i} finished with failure");
}
//private void MethodAsync()
//private async Task MethodAsync()
//private Task MethodAsync()
private async void MethodAsync()
{
//await Task.Delay(1000);
throw new Exception("Ex!");
}
}
}