There's always a chance something goes wrong in a program — a missing file, a network failure, a bad array index, invalid user input, you name it. Exception handling lets you handle errors safely so the whole app doesn't crash.
csharp
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[10]);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Index is outside the array range.");
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong.");
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Finished checking the array.");
}try, catch, finally
tryblock holds the code that might throw an error.catchhandles the error when one occurs. It's best to catch specific exceptions first.finallyruns whether an error happened or not — handy for cleaning up resources.
You should see
Index is outside the array range. Finished checking the array.Info
⚠️ Best practice
Don't just swallow errors and pretend they never happened. It's much better to show the user a friendly message while logging the details for developers.