Home >Backend Development >C#.Net Tutorial >How to catch exceptions thrown by async void methods in C#?

How to catch exceptions thrown by async void methods in C#?

WBOY
WBOYforward
2023-08-31 12:53:021575browse

如何捕获 C# 中 async void 方法抛出的异常?

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.

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete