In synchronous C# code, an exception propagates up the call stack until it reaches an appropriate catch block that can handle the exception. However, exception handling in asynchronous methods is not that simple.
Asynchronous methods in C# can have three types of return values: void, Task and Task. When an exception occurs in an asynchronous method with a return type of Task or Task , the exception object is wrapped in an AggregateException instance and attached to the Task object.
If multiple exceptions are thrown, all exceptions will be thrown. They are stored in Task objects.
static async Task Main(string[] args) { await DoSomething(); Console.ReadLine(); } public static async Task Foo() { throw new ArgumentNullException(); } public static async Task DoSomething(){ try{ await Foo(); } catch (ArgumentNullException ex){ Console.WriteLine(ex); } }
System.ArgumentNullException: Value cannot be null. at DemoApplication.Program.Foo() in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 37 at DemoApplication.Program.DoSomething() in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 44
The above is the detailed content of How to catch exceptions thrown by async void methods in C#?. For more information, please follow other related articles on the PHP Chinese website!