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
Release: 2023-08-31 12:53:02
forward
1523 people have browsed it

如何捕获 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);
   }
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template