0
0
C Sharp (C#)programming~30 mins

Exception handling in async code in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Exception handling in async code
📖 Scenario: You are building a simple program that fetches data asynchronously. Sometimes, the fetch might fail, and you want to handle those errors gracefully.
🎯 Goal: Learn how to handle exceptions in asynchronous methods using try-catch blocks in C#.
📋 What You'll Learn
Create an async method that simulates data fetching
Add a boolean variable to control if the fetch should fail
Use a try-catch block to handle exceptions in the async method call
Print the result or error message
💡 Why This Matters
🌍 Real World
Handling errors in asynchronous operations is important in real-world apps like web requests, file access, or database calls to keep the app stable.
💼 Career
Knowing how to catch and handle exceptions in async code is a key skill for C# developers working on modern applications that use asynchronous programming.
Progress0 / 4 steps
1
Create an async method to fetch data
Write an async method called FetchDataAsync that returns a Task<string>. Inside, use await Task.Delay(500) to simulate waiting, then return the string "Data fetched successfully".
C Sharp (C#)
Need a hint?

Use async Task<string> as the method signature and await Task.Delay(500) to simulate delay.

2
Add a boolean to control failure
Add a public static boolean variable called shouldFail in the Program class and set it to false. Modify FetchDataAsync to throw an Exception with message "Fetch failed" if shouldFail is true.
C Sharp (C#)
Need a hint?

Use if (shouldFail) to check the boolean and throw new Exception("Fetch failed") to raise an error.

3
Use try-catch to handle exceptions
In the Main method, call FetchDataAsync inside a try block and await its result. Use a catch (Exception ex) block to catch exceptions. Store the result or the exception message in a string variable called output.
C Sharp (C#)
Need a hint?

Use try and catch (Exception ex) to handle errors. Assign the awaited call result or exception message to output.

4
Print the output
Add a line in the Main method to print the output variable using Console.WriteLine(output).
C Sharp (C#)
Need a hint?

Use Console.WriteLine(output) to show the result or error message.