C# exceptions, finally, and using

An exception interrupts normal flow and is passed up the call stack until a matching catch block handles it. Define a custom exception by deriving from Exception and add the data the handler needs. A catch can add a when filter, so it handles the exception only if a condition is true. A finally block runs whether or not an exception occurred, which makes it the place for clean-up.

C#
using System;

class InsufficientFundsException : Exception {
  public int Missing { get; }

  public InsufficientFundsException(int missing) : base("short by " + missing) {
    Missing = missing;
  }
}

class Connection : IDisposable {
  public void Dispose() {
    Console.WriteLine("connection closed");
  }
}

class Program {
  static int Withdraw(int balance, int amount) {
    if (amount > balance) {
      throw new InsufficientFundsException(amount - balance);
    }
    return balance - amount;
  }

  static void Main() {
    try {
      using (var connection = new Connection()) {
        Console.WriteLine("working");
        Withdraw(50, 80);
        Console.WriteLine("not reached");
      }
    } catch (InsufficientFundsException e) when (e.Missing > 10) {
      Console.WriteLine("caught: " + e.Message);
    } finally {
      Console.WriteLine("finally");
    }

    if (!int.TryParse("12x", out int value)) {
      Console.WriteLine("TryParse failed without an exception");
    }
  }
}
Read the full lesson