C# uses try, catch, and finally blocks to handle exceptions — preventing runtime crashes and allowing clean recovery.
try
{
int[] arr = { 1, 2, 3 };
Console.WriteLine(arr[10]); // IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Array error: {ex.Message}");
}
try
{
string input = Console.ReadLine();
int number = int.Parse(input);
int result = 100 / number;
Console.WriteLine($"Result: {result}");
}
catch (FormatException)
{
Console.WriteLine("Please enter a valid number.");
}
catch (DivideByZeroException)
{
Console.WriteLine("Cannot divide by zero.");
}
catch (Exception ex) // catch-all
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
StreamReader? reader = null;
try
{
reader = new StreamReader("data.txt");
Console.WriteLine(reader.ReadToEnd());
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found.");
}
finally
{
reader?.Dispose(); // always runs — even if exception occurred
}
try { /* risky */ }
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("Resource not found (404).");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP error: {ex.StatusCode}");
}