![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to catch an exception thrown by an async void method in C#?
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
Advertisements