How to catch an exception thrown by an async void method in C#?

CsharpServer Side ProgrammingProgramming

In synchronous C# code, the exceptions are propagated up the call stack until they reach an appropriate catch block that can handle the exception. However, exception handling in asynchronous methods is not as straightforward.

An asynchronous method in C# can have three types of return value: void, Task, and Task. When an exception occurs in an async method that has a return type of Task or Task, the exception object is wrapped in an instance of AggregateException and attached to the Task object.

If multiple exceptions are thrown, all of them are stored in the Task object.

Example 1

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);
   }
}

Output

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
raja
Published on 25-Nov-2020 16:23:15
Advertisements