You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Modern applications must handle I/O operations (network calls, file access, database queries) without blocking. C# provides a first-class async/await model built on the Task type. This lesson also covers structured error handling with exceptions.
try
{
string content = File.ReadAllText("data.txt");
int number = int.Parse(content);
Console.WriteLine($"Result: {number}");
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File not found: {ex.FileName}");
}
catch (FormatException ex)
{
Console.WriteLine($"Invalid format: {ex.Message}");
}
catch (Exception ex)
{
// Catch-all for unexpected exceptions
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
// Always runs — cleanup code
Console.WriteLine("Cleanup complete");
}
| Exception | When |
|---|---|
Exception | Base class for all exceptions |
SystemException | Base for runtime exceptions |
ArgumentException | Invalid argument |
ArgumentNullException | Null argument |
InvalidOperationException | Operation not valid for current state |
NullReferenceException | Accessing a member on null |
IndexOutOfRangeException | Array index out of bounds |
IOException | I/O operation failed |
HttpRequestException | HTTP request failed |
TaskCanceledException | Task was cancelled |
public void SetAge(int age)
{
if (age < 0)
throw new ArgumentOutOfRangeException(nameof(age), "Age cannot be negative");
Age = age;
}
public class InsufficientFundsException : Exception
{
public decimal Balance { get; }
public decimal Amount { get; }
public InsufficientFundsException(decimal balance, decimal amount)
: base($"Cannot withdraw {amount:C}. Balance: {balance:C}")
{
Balance = balance;
Amount = amount;
}
}
try
{
await httpClient.GetAsync(url);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("Resource not found");
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Not authorised");
}
Automatically dispose of resources when done:
// Traditional using block
using (var reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
}
// reader is disposed here
// Modern using declaration (C# 8+)
using var reader2 = new StreamReader("file.txt");
string content2 = reader2.ReadToEnd();
// reader2 is disposed when the enclosing scope ends
Synchronous I/O blocks the calling thread:
// BAD — blocks the thread while waiting
string content = httpClient.GetStringAsync(url).Result;
Asynchronous I/O releases the thread while waiting:
// GOOD — thread is free while waiting
string content = await httpClient.GetStringAsync(url);
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.