Try and Catch: The Safety Harness

Try and Catch: The Safety Harness in C#: A steelworker on the fortieth floor does not walk the beam hoping nothing goes wrong.

The Analogy: The Harness on the Scaffold

A steelworker on the fortieth floor does not walk the beam hoping nothing goes wrong. They clip a harness to an anchor point first. The harness does not stop them slipping — slipping is a fact of life at that height. What it does is decide what happens next: instead of falling forty floors, they drop half a metre, dangle, swear, and climb back on.

Notice three things about that harness, because they map exactly onto C# error handling. First, it is attached before the risky step, not after the slip. Second, it is attached to the smallest useful span of the walk — you clip on for the beam, not for the whole building, because a harness clipped to everything would let you swing into a wall. Third, it turns an unrecoverable event into a recoverable one; the worker still knows they slipped, and the site log still records it.

A try block is that clip-on. You wrap the step that might fail, you say what to do if it does, and you say what must happen either way. What you get is not code that cannot fail — no such code exists once you touch files, networks, users, or arithmetic. What you get is a program that fails at a place you chose, with information you chose, instead of vanishing with a wall of red text.


Syntax or Core Structure

An exception is an object that is thrown at the point of failure and caught by the nearest enclosing handler that matches its type. Everything between the throw and the catch is abandoned.

using System;

class Program
{
    static void Main()
    {
        int[] readings = { 12, 7, 3 };

        // 1. try / catch: the failing statement abandons the rest of the block.
        try
        {
            Console.WriteLine("reading 1: " + readings[1]);
            Console.WriteLine("reading 9: " + readings[9]);   // throws here
            Console.WriteLine("never reached");
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("no such reading");
        }

        // 2. finally always runs - even when the try block returns a value.
        Console.WriteLine(Divide(10, 2));
        Console.WriteLine(Divide(10, 0));

        // 3. Several catch blocks: the FIRST matching type wins, so order
        //    them most specific first.
        Console.WriteLine(Describe("41"));
        Console.WriteLine(Describe("forty"));
        Console.WriteLine(Describe(null));

        Console.WriteLine("still running");
    }

    static string Divide(int a, int b)
    {
        try
        {
            return "quotient " + (a / b);
        }
        catch (DivideByZeroException)
        {
            return "undefined";
        }
        finally
        {
            // Runs after the return value is computed, before the caller
            // sees it. Use it for cleanup that must happen either way.
            Console.WriteLine("  (divide finished)");
        }
    }

    static string Describe(string? text)
    {
        try
        {
            int age = int.Parse(text!);
            return "age " + age;
        }
        catch (FormatException)
        {
            return "not a number";
        }
        catch (ArgumentNullException)
        {
            return "nothing supplied";
        }
    }
}

Output:

reading 1: 7
no such reading
  (divide finished)
quotient 5
  (divide finished)
undefined
age 41
not a number
nothing supplied
still running

Read the middle of that output slowly, because it surprises people: (divide finished) appears before quotient 5. The finally block runs while the method is on its way out, and only then does the caller get the value to print. finally is not "code after the try" — it is code that runs on every exit path, including return, including an exception nobody caught.


Technical Depth: What a Throw Actually Does

Every exception in .NET derives from System.Exception, and that single root is why one catch (Exception) can catch anything. The types you will meet most are worth learning by their meaning, not their spelling:

ExceptionThrown whenWhose fault is it
ArgumentNullExceptionA required argument was nullThe caller's
ArgumentOutOfRangeExceptionAn argument is outside the allowed rangeThe caller's
ArgumentExceptionAn argument is wrong in some other wayThe caller's
InvalidOperationExceptionThe object is in the wrong state for this callThe caller's
FormatExceptionText does not parse as the target typeThe data's
OverflowExceptionThe value does not fit the target typeThe data's
NullReferenceExceptionYou dereferenced nullYours - a bug, not an event
IndexOutOfRangeExceptionArray index outside the boundsYours - a bug
IOExceptionA file, disk or pipe operation failedThe world's
OperationCanceledExceptionA CancellationToken was cancelledNobody's - it is normal

That last column is the one that matters when you decide whether to catch. NullReferenceException and IndexOutOfRangeException mean your logic is wrong; catching them hides a defect you should fix. IOException means the world moved — a USB stick was pulled out — and catching it is exactly right.

The two passes, and why when exists

The CLR handles a throw in two passes. First it walks up the call stack asking each handler "does this one match?" — that is the filter pass, and no stack frame is destroyed yet. Only once a handler says yes does the second pass run finally blocks and unwind the frames down to it. An exception filter (catch (X) when (condition)) is evaluated during the first pass, so if it returns false the stack is still fully intact and untouched:

catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.TooManyRequests)
{
    await Task.Delay(1000);       // retry only this one case
}

Written the other way — catch, test inside, throw; if it is not yours — the stack has already unwound by the time you decide, so a debugger stopping on "first chance" no longer shows you the original frame. Filters are not a style preference; they preserve evidence.

Rethrowing without destroying the trace

FormEffect on the stack traceUse when
throw;Preserved from the original throw siteYou handled part of it and want it to keep going up
throw ex;Reset to this line - original site lostEssentially never
throw new X("...", ex)New trace, original kept as InnerExceptionYou are adding context at a layer boundary

throw ex; inside a catch (Exception ex) is the single most common way a team loses a stack trace: the log then points at the catch block instead of the line that actually broke.

Exceptions are not control flow

A throw costs roughly a few microseconds — thousands of times a simple if. In a loop over a million rows, "try to parse, catch the failures" is measurably slow, and it is also harder to read. That is what the Try family is for:

Failure is...UseCost
Expected, common (user typed text)int.TryParse, dict.TryGetValueJust a branch
Unexpected, rare (disk vanished)try / catchMicroseconds, once
if (int.TryParse(input, out int value))    // no exception thrown at all
    Console.WriteLine(value * 2);
else
    Console.WriteLine("not a number");

finally you rarely have to write

Nine times in ten, finally exists to release something. C# has a shorter spelling for that: using, which calls Dispose() on the way out of scope, exception or not.

using var reader = new StreamReader("data.csv");   // disposed at end of method
string? first = reader.ReadLine();

That is compiled into a try { ... } finally { reader?.Dispose(); }. Writing the finally by hand for a stream, connection or lock is a sign you have forgotten using exists.


Real World Example: Importing a Sensor Log

A day's readings arrive as text from a device that is only mostly reliable. Some lines are blank, one is corrupt, one overflowed, and one is physically impossible. The import must not stop at the first bad line — it must report each one and keep going, then tell you how much of the day survived.

using System;

class Program
{
    static void Main()
    {
        string[] rows = { "12", "7", "abc", "", "99999999999999999999", "-3", "40" };
        int total = 0, used = 0, skipped = 0;

        foreach (string row in rows)
        {
            try
            {
                total += ParseReading(row);
                used++;
                Console.WriteLine("ok      " + row);
            }
            catch (FormatException)
            {
                skipped++;
                Console.WriteLine("skip    '" + row + "' is not a number");
            }
            catch (OverflowException)
            {
                skipped++;
                Console.WriteLine("skip    '" + row + "' is too large for int");
            }
            catch (ArgumentOutOfRangeException ex) when (ex.ActualValue is int v)
            {
                skipped++;
                Console.WriteLine("skip    " + v + " is below zero");
            }
        }

        Console.WriteLine($"total {total} from {used} readings, {skipped} skipped");
    }

    // Parse throws FormatException or OverflowException on bad text; the
    // range rule is ours, so we throw it ourselves with the offending value.
    static int ParseReading(string row)
    {
        int value = int.Parse(row);

        if (value < 0)
            throw new ArgumentOutOfRangeException(nameof(row), value, "readings cannot be negative");

        return value;
    }
}

Output:

ok      12
ok      7
skip    'abc' is not a number
skip    '' is not a number
skip    '99999999999999999999' is too large for int
skip    -3 is below zero
ok      40
total 59 from 3 readings, 4 skipped

Three details are doing the real work here. The try sits inside the loop, not around it, so one bad row costs one row. Each catch names a type it can genuinely explain, so the log tells a human what to fix rather than printing a class name. And ArgumentOutOfRangeException is constructed with the parameter name and the actual value, which is why the filter can pull -3 back out with ex.ActualValue is int v instead of parsing it out of a message string.


Common Mistakes

  1. Catching Exception everywhere. A blanket catch (Exception) in the middle of your code swallows NullReferenceException bugs alongside real IO failures, and the program limps on with corrupt state. Catch broadly only at a boundary — a request handler, a background loop, Main — where the alternative is a crash.
  2. An empty catch block. catch { } says "I know this can fail and I have decided not to tell anyone." Six months later a feature is silently doing nothing and the log is spotless. If you truly can ignore it, log it at debug level and write down why.
  3. throw ex; instead of throw;. This resets the stack trace to the current line, so the very information you were catching the exception to record is destroyed.
  4. Catch order from general to specific. catch (Exception) before catch (FormatException) will not compile — CS0160, "a previous catch clause already catches all exceptions" — because the later block is unreachable. Order specific first.
  5. Using exceptions as flow control. Wrapping int.Parse in a try for every row of a million-row file is both slower and less readable than int.TryParse. Reserve exceptions for the genuinely exceptional.
  6. Returning from finally. A return inside finally discards the exception that was travelling, so the failure disappears without a trace. C# forbids return in a finally for this reason in some contexts and it is a bug in all of them.
  7. Losing the inner exception. throw new InvalidOperationException("import failed") throws away the IOException that explains why. Pass it as the second constructor argument so it survives as InnerException.
  8. Logging the message only. ex.Message is one sentence with no file and no line. Log ex.ToString() (or hand the exception object to your logger) so the type, message, stack trace and inner exceptions all land in the log together.

Best Practices

  • Catch the narrowest type you can actually handle, and let everything else travel up to a boundary that knows what to do about it.
  • Use when filters instead of catch-test-rethrow, so unmatched exceptions never unwind the stack in the first place.
  • Prefer TryParse / TryGetValue for failures you expect; save try/catch for failures you do not.
  • Use using (or using var) for anything disposable rather than hand-writing finally { x.Dispose(); }.
  • Validate arguments at the top of a public method and throw ArgumentNullException.ThrowIfNull(x) or ArgumentOutOfRangeException.ThrowIfNegative(n) — one line each, with the parameter name filled in for you.
  • When you wrap an exception to add context, always pass the original as the inner exception.
  • Never let a catch block leave the object half-modified: change state after the risky call succeeds, not before.
  • Log the whole exception object once, at the place that decides the outcome — not at every level on the way up, which produces the same failure five times in the log.

Practice Exercises

  1. Safe average. Write double Average(int[] values) that returns the mean. Call it with an empty array and observe the DivideByZeroException... or the NaN. Explain which one you actually get for int division versus double division, then make the method throw ArgumentException with a clear message for an empty array.
  2. Order the catches. Write a method that parses a string into an int and deliberately put catch (Exception) before catch (FormatException). Note the compiler error number and message, then fix the order and confirm both blocks are reachable.
  3. Prove finally runs. Write a method with a return inside try, a Console.WriteLine inside finally, and a second WriteLine after the whole try statement. Predict the order of the three lines before you run it, then run it and reconcile any difference.
  4. Retry with a filter. Write int Fetch(int attempt) that throws TimeoutException for the first two attempts and returns 42 on the third. Call it in a loop that catches TimeoutException only when the attempt number is below 3, and let the third failure escape. Verify that a genuine fourth-attempt failure still crashes the program.