Skip to main content
๐Ÿ“œ WAYPOINT LESSON

finally, using, and validate-early

โญ beginnerโณ 12 min read๐Ÿ“ Lesson 52 of 85

Cleanup runs no matter what; validation happens before any work โ€” not inside a catch.

finally: always runs

try
{
    OpenConnection();
    DoWork();          // may throw
}
finally
{
    CloseConnection(); // runs on success AND on failure
}

finally executes whether the try block succeeds, throws, or returns. Put cleanup there โ€” resource release must never depend on luck.

In modern C#, files/streams take that shape for you:

using (var reader = new StringReader(text))
{
    ... // disposed automatically, even on exception
}

Validate early, fail fast

The strongest error-handling pattern isn't a catch โ€” it's refusing bad input before any work happens:

static int ParseAge(string input)
{
    if (input == null) throw new ArgumentException("input required");
    if (!int.TryParse(input, out int age))
        throw new FormatException("not a number");
    if (age < 0 || age > 150)
        throw new ArgumentOutOfRangeException("implausible age");
    return age;
}

Compare with catching errors after half the work is done: state is now inconsistent, cleanup is complicated, and the failure message is vague. Validate at the door.

โšก Now practice

Ready to Code
Error handling workoutParsers, transfers, retries, and custom types โ€” contracts under discriminating tests.
4 challenges ยท ยท ~40 min