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

Exception handling in async code in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Async Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of async method with try-catch
What is the output of this C# program when run?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        try {
            await ThrowExceptionAsync();
        } catch (Exception ex) {
            Console.WriteLine($"Caught: {ex.Message}");
        }
    }

    static async Task ThrowExceptionAsync() {
        await Task.Delay(10);
        throw new InvalidOperationException("Error happened");
    }
}
ACaught: Error happened
BCaught: System.InvalidOperationException
CNo output
DUnhandled exception: Error happened
Attempts:
2 left
💡 Hint
Remember that exceptions thrown inside awaited async methods can be caught by try-catch around the await.
❓ Predict Output
intermediate
2:00remaining
Exception behavior without await
What happens when this C# program runs?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        try {
            ThrowExceptionAsync();
        } catch (Exception ex) {
            Console.WriteLine($"Caught: {ex.Message}");
        }
        await Task.Delay(50);
        Console.WriteLine("End of Main");
    }

    static async Task ThrowExceptionAsync() {
        await Task.Delay(10);
        throw new InvalidOperationException("Error happened");
    }
}
AEnd of Main
B
Caught: Error happened
End of Main
C
End of Main
Unhandled exception: Error happened
DCaught: System.InvalidOperationException
Attempts:
2 left
💡 Hint
Think about what happens if you don't await an async method that throws an exception.
🔧 Debug
advanced
2:00remaining
Identify the cause of unhandled exception
Why does this program crash with an unhandled exception despite the try-catch block?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        try {
            var task = ThrowExceptionAsync();
        } catch (Exception ex) {
            Console.WriteLine($"Caught: {ex.Message}");
        }
        await Task.Delay(50);
    }

    static async Task ThrowExceptionAsync() {
        await Task.Delay(10);
        throw new InvalidOperationException("Error happened");
    }
}
AThe Task.Delay prevents the exception from being thrown.
BThe try-catch block syntax is incorrect and does not catch exceptions.
CThe exception is swallowed silently and does not crash the program.
DThe exception is thrown after the try-catch block because the task is not awaited inside the try.
Attempts:
2 left
💡 Hint
Consider when exceptions in async methods are observed and caught.
📝 Syntax
advanced
2:00remaining
Which code snippet correctly catches exceptions from multiple awaited tasks?
Select the code snippet that correctly catches exceptions from two async methods awaited in parallel.
A
var t1 = Task1Async();
var t2 = Task2Async();
try {
    await t1;
    await t2;
} catch (Exception ex) {
    Console.WriteLine($"Caught: {ex.Message}");
}
B
try {
    var t1 = Task1Async();
    var t2 = Task2Async();
    await Task.WhenAll(t1, t2);
} catch (Exception ex) {
    Console.WriteLine($"Caught: {ex.Message}");
}
C
try {
    await Task1Async();
    await Task2Async();
} catch (Exception ex) {
    Console.WriteLine($"Caught: {ex.Message}");
}
D
try {
    Task.WaitAll(Task1Async(), Task2Async());
} catch (Exception ex) {
    Console.WriteLine($"Caught: {ex.Message}");
}
Attempts:
2 left
💡 Hint
Think about how to await multiple tasks and catch exceptions from all of them.
🚀 Application
expert
3:00remaining
Determine the final value after exception handling in async code
What is the value of variable 'result' after this code runs?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static int result = 0;

    static async Task Main() {
        try {
            await MethodA();
        } catch {
            result += 10;
        }
        result += 1;
        Console.WriteLine(result);
    }

    static async Task MethodA() {
        try {
            await MethodB();
        } catch {
            result += 5;
            throw;
        }
    }

    static async Task MethodB() {
        await Task.Delay(10);
        throw new Exception("Fail");
    }
}
A16
B6
C11
D1
Attempts:
2 left
💡 Hint
Trace the increments to 'result' through nested try-catch and rethrow.

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