CSharp · Console
using System;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
// The exception is thrown on a pool thread and stored in the task.
// The process does not crash; the task becomes Faulted.
var t = Task.Run(() => int.Parse("abc"));
// 1. Wait() wraps the exception in an AggregateException
try { t.Wait(); }
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
Console.WriteLine($" inner: {ex.InnerException?.GetType().Name}");
}
// 2. await unwraps and rethrows the original exception
try { await t; }
catch (Exception ex) { Console.WriteLine(ex.GetType().Name); }
Console.WriteLine($"\nTask status: {t.Status}"); // Faulted, and it stays that way
// 3. Result also wraps (same as Wait)
try { var r = t.Result; }
catch (Exception ex) { Console.WriteLine($"Result: {ex.GetType().Name}"); }
// 4. GetAwaiter().GetResult() unwraps like await, but blocks the thread
try { t.GetAwaiter().GetResult(); }
catch (Exception ex) { Console.WriteLine($"GetAwaiter().GetResult(): {ex.GetType().Name}"); }
// 5. The classic bug: this catch never runs
try
{
try { t.Wait(); }
catch (FormatException) { Console.WriteLine("Caught FormatException"); } // never runs
}
catch (Exception ex)
{
Console.WriteLine($"\nClassic bug: the FormatException catch was skipped, got {ex.GetType().Name}");
}
}
}