Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Exception handling in async code in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Exception handling in async code
Start async method
↓
Await async operation
↓
Exception thrown?
No→Continue execution
Yes↓
Catch exception
↓
Handle exception or rethrow
↓
End async method
This flow shows how an async method awaits an operation, checks for exceptions, catches them if any, and then handles or rethrows before finishing.
Execution Sample
C Sharp (C#)
async Task<int> GetNumberAsync()
{
    try
    {
        int result = await Task.Run<int>(() => throw new Exception("Fail"));
        return result;
    }
    catch (Exception ex)
    {
        return -1;
    }
}
This async method runs a task that throws an exception, catches it, and returns -1 instead.
Execution Table
StepActionEvaluationResult
1Start GetNumberAsyncNo exception yetMethod started
2Await Task.Run throwing ExceptionException thrown inside TaskException propagates to await
3Catch block triggeredException caught as exCatch block entered
4Return -1 from catchReturn value set to -1Method returns -1
5Method completesNo further codeExecution ends
💡 Exception thrown inside awaited task is caught by catch block, so method returns -1 and completes normally.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
resultundefinedexception thrown, no valueundefinedundefined
exnullnullException objectException object
Key Moments - 3 Insights
Why doesn't the exception crash the program immediately?
Because the exception happens inside the awaited Task, it is caught by the catch block in the async method (see Step 3 in execution_table), preventing a crash.
What happens if we don't catch the exception inside the async method?
If uncaught, the exception would propagate to the caller of the async method, potentially causing an unhandled exception error.
Why do we return -1 in the catch block?
Returning -1 is a way to signal failure gracefully instead of throwing, as shown in Step 4 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'result' after Step 2?
A-1
BUndefined because exception was thrown
C0
DException object
💡 Hint
Check Step 2 in execution_table where exception is thrown before 'result' can be assigned.
At which step does the catch block handle the exception?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
See execution_table Step 3 where catch block is triggered.
If the catch block was removed, what would happen after Step 2?
AException propagates to caller and method does not return normally
BMethod returns -1 anyway
CException is ignored and method continues
DMethod returns 0
💡 Hint
Without catch, exception is not handled inside method, so it propagates (see key_moments #2).
Concept Snapshot
async Task Method with try-catch:
- Await async operation inside try
- If exception thrown, catch block runs
- Handle exception or return fallback
- Prevents unhandled exceptions
- Keeps async flow safe and predictable
Full Transcript
This visual trace shows how exception handling works inside async code in C#. The async method starts and awaits a Task that throws an exception. Instead of crashing, the exception is caught by the catch block inside the async method. The catch block returns -1 to signal failure. Variables like 'result' remain undefined when the exception occurs, and the exception object is stored in 'ex'. This prevents the program from crashing and allows graceful error handling. If the catch block was missing, the exception would propagate to the caller and could cause an unhandled exception error. This pattern helps keep async code safe and predictable.

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

  1. Step 1: Understand async exception behavior

    Exceptions in async methods are thrown when awaited, so they must be caught around await.
  2. Step 2: Purpose of try-catch

    Using try and catch around await lets you handle errors gracefully and avoid crashes.
  3. Final Answer:

    To catch exceptions thrown during asynchronous operations and prevent program crashes. -> Option A
  4. 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()?
easy
A. await try { DoWorkAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); }
B. try { await DoWorkAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); }
C. try { DoWorkAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); }
D. DoWorkAsync().catch(ex => Console.WriteLine(ex.Message));

Solution

  1. Step 1: Identify correct try-catch with await

    The await keyword must be inside the try block to catch exceptions properly.
  2. Step 2: Check syntax correctness

    try { await DoWorkAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } correctly places await DoWorkAsync() inside try and catches exceptions.
  3. Final Answer:

    try { await DoWorkAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } -> Option B
  4. Quick Check:

    await inside try = correct syntax [OK]
Hint: Put await inside try, not outside [OK]
Common Mistakes:
  • Placing await outside try block
  • Missing await keyword
  • Using incorrect catch syntax
3. What will be the output of the following code?
async Task TestAsync()
{
    try
    {
        await Task.Run(() => throw new InvalidOperationException("Error occurred"));
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine("Caught: " + ex.Message);
    }
}

await TestAsync();
medium
A. Unhandled exception crash
B. No output, program runs silently
C. Caught: Error occurred
D. Compilation error

Solution

  1. Step 1: Analyze async exception throwing

    The Task.Run throws an InvalidOperationException inside the task.
  2. Step 2: Exception caught in catch block

    The await inside try catches the exception, printing the message.
  3. Final Answer:

    Caught: Error occurred -> Option C
  4. Quick Check:

    Exception caught and message printed [OK]
Hint: Exceptions in awaited tasks are caught by surrounding try [OK]
Common Mistakes:
  • Expecting no output
  • Thinking exception crashes program
  • Missing await causes unhandled exceptions
4. Identify the error in this async exception handling code:
async Task RunAsync()
{
    try
    {
        Task.Delay(1000);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + ex.Message);
    }
}

await RunAsync();
medium
A. Missing await before Task.Delay, so exceptions won't be caught.
B. Try-catch cannot be used with async methods.
C. Task.Delay does not throw exceptions, so catch is useless.
D. Catch block syntax is incorrect.

Solution

  1. Step 1: Check await usage

    The Task.Delay(1000) is called without await, so exceptions won't be observed here.
  2. Step 2: Effect on exception handling

    Without await, the try-catch does not catch exceptions from the async call.
  3. Final Answer:

    Missing await before Task.Delay, so exceptions won't be caught. -> Option A
  4. Quick Check:

    Await missing = exceptions not caught [OK]
Hint: Always await async calls inside try to catch exceptions [OK]
Common Mistakes:
  • Forgetting await before async calls
  • Assuming try-catch works without await
  • Believing Task.Delay throws exceptions here
5. You have two async methods:
async Task MethodA()
{
    await Task.Delay(500);
    throw new Exception("Error in A");
}

async Task MethodB()
{
    try
    {
        await MethodA();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Caught in B: " + ex.Message);
        throw;
    }
}

try
{
    await MethodB();
}
catch (Exception ex)
{
    Console.WriteLine("Caught in main: " + ex.Message);
}

What will be the output when this code runs?
hard
A. No output, exception swallowed
B. Caught in B: Error in A
C. Caught in main: Error in A
D. Caught in B: Error in A Caught in main: Error in A

Solution

  1. Step 1: Exception thrown in MethodA

    MethodA throws an exception after delay.
  2. Step 2: Exception caught and rethrown in MethodB

    MethodB catches the exception, prints message, then rethrows it.
  3. Step 3: Exception caught again in main

    Main try-catch catches the rethrown exception and prints its message.
  4. Final Answer:

    Caught in B: Error in A Caught in main: Error in A -> Option D
  5. Quick Check:

    Exception caught twice due to rethrow [OK]
Hint: Rethrow exceptions to propagate them up the call stack [OK]
Common Mistakes:
  • Assuming exception is swallowed after first catch
  • Missing that rethrow sends exception to caller
  • Expecting only one catch message printed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard