📖 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#)
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#)
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#)
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#)
Hint
Use Console.WriteLine(output) to show the result or error message.
Practice
(1/5)
1. What is the main purpose of using try and catch blocks around await calls in C# async code?
easy
A. To catch exceptions thrown during asynchronous operations and prevent program crashes.
B. To make the async method run faster.
C. To convert async methods into synchronous methods.
D. To automatically retry the async operation if it fails.
Solution
Step 1: Understand async exception behavior
Exceptions in async methods are thrown when awaited, so they must be caught around await.
Step 2: Purpose of try-catch
Using try and catch around await lets you handle errors gracefully and avoid crashes.
Final Answer:
To catch exceptions thrown during asynchronous operations and prevent program crashes. -> Option A
Quick Check:
try-catch around await = catch exceptions [OK]
Hint: Always put await inside try to catch errors [OK]
Common Mistakes:
Assuming async methods never throw exceptions
Catching exceptions outside async calls
Using try-catch without await inside
2. Which of the following is the correct syntax to catch exceptions from an async method DoWorkAsync()?