When your program does tasks that take time, like reading files or talking to the internet, it uses async code. Sometimes things go wrong, so you need a way to catch and handle errors without stopping everything.
0
0
Exception handling in async code in C Sharp (C#)
Introduction
When downloading data from the internet and you want to handle connection problems.
When reading or writing files asynchronously and need to catch file errors.
When calling a slow database query asynchronously and want to handle timeouts.
When running multiple tasks at once and want to catch errors from any of them.
Syntax
C Sharp (C#)
try { await SomeAsyncMethod(); } catch (Exception ex) { // Handle the error here }
Use try and catch blocks around await calls to catch exceptions.
Always catch specific exceptions if possible, but Exception catches all errors.
Examples
This example waits 1 second, then throws an error, which is caught and printed.
C Sharp (C#)
try { await Task.Delay(1000); throw new InvalidOperationException("Oops!"); } catch (InvalidOperationException ex) { Console.WriteLine($"Caught error: {ex.Message}"); }
This catches any error from
SomeAsyncMethod and prints a message.C Sharp (C#)
try { await SomeAsyncMethod(); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); }
Sample Program
This program runs an async method that waits half a second then throws an error. The error is caught in Main and printed.
C Sharp (C#)
using System; using System.Threading.Tasks; class Program { static async Task Main() { try { await DoWorkAsync(); } catch (Exception ex) { Console.WriteLine($"Caught an exception: {ex.Message}"); } } static async Task DoWorkAsync() { await Task.Delay(500); throw new InvalidOperationException("Something went wrong in async code."); } }
OutputSuccess
Important Notes
Always use await inside try blocks to catch exceptions properly.
If you forget await, exceptions may not be caught where you expect.
For multiple async tasks, consider using Task.WhenAll and catch exceptions after awaiting.
Summary
Use try and catch around await calls to handle errors in async code.
Catching exceptions prevents your program from crashing unexpectedly.
Always await async methods inside try blocks to catch errors correctly.