C# Intermediate: OOP, Interfaces & Events

Lesson 4 of 7

Exception Handling

Things go wrong at runtime: a file is missing, a network call times out, a user types letters into a number field. Exceptions let you handle that without crashing the whole program.

try
{
    int[] scores = { 90, 85, 77 };
    Console.WriteLine(scores[5]); // out of range
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine($"Invalid index: {ex.Message}");
}
finally
{
    Console.WriteLine("Always runs, whether or not an exception happened.");
}

The pieces

  • try wraps code that might throw.
  • catch (SomeException ex) runs if that exception type (or a subclass of it) is thrown inside the try block, you can stack multiple catch blocks for different exception types.
  • finally runs no matter what, whether the try succeeded, threw, or the catch itself re-threw, use it for cleanup (closing a file, releasing a resource).
  • throw raises an exception yourself: throw new ArgumentException("amount must be positive");.

Custom exceptions

class InsufficientXpException : Exception
{
    public InsufficientXpException(string message) : base(message) { }
}

if (xp < required)
    throw new InsufficientXpException($"Need {required} XP, only have {xp}.");

A custom exception inherits from Exception (or a more specific built-in one) and gives calling code something precise to catch, instead of catching the broad, generic Exception.

📝 Exception Handling Quiz

Passing score: 70%
  1. 1.Which block always runs, whether or not an exception was thrown?

  2. 2.The ____ keyword raises an exception yourself.

  3. 3.A custom exception class typically inherits from Exception.