This entry is part 2 of 2 in the series How C# Got Here.

How C# Got Here.

Paying Off the Billion-Dollar Mistake

Throw, Catch, Finally, Return


The most important exception feature in C# is one it doesn’t have.

In Java, a method that can throw an IOException has to say so in its signature, and every caller has to catch it or declare it in turn. These are checked exceptions. C# 1.0 shipped in 2002 without them, and that was a deliberate choice.

In a 2003 interview with Bill Venners and Bruce Eckel, C#’s lead designer Anders Hejlsberg gave two reasons. The first was versioning. If version two of a method can throw one more exception than version one, every caller that doesn’t handle it breaks. The second was scale. Combine a few subsystems that each throw a handful of exceptions, and the throws clauses grow to dozens of entries. In practice, he said, programmers get around that by declaring throws Exception everywhere or by writing empty catch blocks, and the code ends up worse for it.

He also said C# was staying neutral until a better solution turned up. Keep that in mind. It comes back at the end.

This is the second post in a series that follows one problem at a time through C#’s history. The first one was about null. This one is about what happens after something goes wrong.

The first post was organised by era. This one is organised by keyword, because throw, catch and finally have each had their own timeline. At the end, a fourth keyword turns up as an alternative to all three: return.

Here’s our running example, a method that loads a settings file, as you might have written it in C# 1.0:

public Settings LoadSettings(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Trim().Length == 0)
    {
        throw new ArgumentException("Path cannot be empty.", "path");
    }

    try
    {
        using (StreamReader reader = new StreamReader(path))
        {
            return Settings.Parse(reader.ReadToEnd());
        }
    }
    catch (FileNotFoundException)
    {
        return Settings.Default;
    }
    catch (DirectoryNotFoundException)
    {
        return Settings.Default;
    }
}

A guard clause, a cleanup block, and two handlers that do the same thing. Each section below rewrites one part of it.

throw: guard clauses get shorter

The guard clause has the oldest problem in the method: "path" is just a string. Rename the parameter and the compiler won’t notice, and the exception goes on naming a parameter that no longer exists.

C# 6 (2015) fixed that with nameof, which the compiler checks and rename refactorings update:

throw new ArgumentNullException(nameof(path));

C# 7 (2017) turned throw into an expression, so it can go wherever a value can. The first post showed it after ??. It also works in the conditional operator and in expression-bodied members:

public int Port => _port > 0 ? _port : throw new InvalidOperationException("Port is not configured.");

public void Reload() => throw new NotSupportedException();

Most of the saving came from the class library, with help from the compiler. In the first post, ArgumentNullException.ThrowIfNull picked up the parameter name on its own through C# 10’s [CallerArgumentExpression]. .NET 8 extended the idea to empty strings and out-of-range numbers:

ArgumentException.ThrowIfNullOrWhiteSpace(path);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(options.TimeoutSeconds);

If TimeoutSeconds is zero, the second line throws with this message:

options.TimeoutSeconds ('0') must be a non-negative and non-zero value. (Parameter 'options.TimeoutSeconds')
Actual value was 0.

Look at the parameter name. It’s the whole expression you passed in, not just a variable name.

The first of those two lines replaces our eight-line guard clause.

catch: handling gets smarter

C# 1 gave you catch by type, and codebases soon settled into a habit: catch, log, rethrow. It came with a classic trap:

catch (IOException ex)
{
    Log(ex);
    throw ex;   // should be: throw;
}

throw ex; rethrows the same object but resets its stack trace to this line, so whoever catches it next sees where it was rethrown, not where it went wrong. A bare throw; keeps the original. Both have been in the language since 1.0, and code reviews have been pointing out the difference ever since.

Async raised a new question: where does an exception go when the code that threw it finishes later, possibly on another thread? Since .NET 4 (2010), the answer has been: into the Task. If you waited on the task, you got an AggregateException with the real exception wrapped inside. C# 5 (2012) made await unwrap it and rethrow the original exception with its stack trace, so an ordinary catch works again:

// .NET 4: the real exception is one level down
try
{
    LoadSettingsAsync(path).Wait();
}
catch (AggregateException ex)
{
    Log(ex.InnerException);
}

// C# 5: await rethrows the original
try
{
    Settings settings = await LoadSettingsAsync(path);
}
catch (IOException ex)
{
    Log(ex);
}

Exceptions in async code deserve more than a paragraph, from async void to Task.WhenAll, but that’s a story for a post about async.

The biggest change came in C# 6 (2015): exception filters. A when clause decides whether a catch block takes the exception at all. That fixes the duplicate handlers in our example:

catch (IOException ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
{
    return Settings.Default;
}

The or pattern arrived in C# 9 (2020); before that, you’d write ||. C# never got Java 7’s multi-catch syntax, catch (A | B e), but a filter does the same job, and it can test anything, not just the type.

Filters weren’t new to .NET. When Mads Torgersen announced them for C# 6 in 2014, he described them as a runtime capability that Visual Basic and F# already exposed. C# was catching up. His preview also used a different keyword, catch (MyException e) if (myfilter(e)). By the time C# 6 shipped, if had become when.

What makes filters more than shorthand is when they run. A filter is evaluated before the stack unwinds, while the method that threw is still on the stack with its local variables intact. That allows a trick most C# developers have never seen: logging an exception without catching it.

try
{
    ProcessOrder(order);
}
catch (Exception ex) when (LogAndContinue(ex))
{
    // never runs
}

static bool LogAndContinue(Exception ex)
{
    Log(ex);
    return false;
}

The filter logs and returns false, so the catch block never runs and the exception carries on up the stack as if nothing had touched it. In Torgersen’s words, filters “leave the stack unharmed”. If nothing else handles the exception, the debugger stops where it was actually thrown, with the local variables intact, not at a rethrow.

Two things about filters surprise people. Because they run before unwinding, they also run before any finally blocks between the throw and the catch. And if a filter itself throws, that exception is silently swallowed and the filter counts as false. Keep filters short and free of side effects, logging aside.

C# 6 also lifted a C# 5 restriction: you couldn’t await inside a catch or finally block. Async code had to stash the exception in a variable and deal with it after the block, a workaround the announcement admitted was ugly. Now the obvious version works:

catch (IOException ex)
{
    await LogAsync(ex);
    throw;
}

finally: cleanup gets shorter

In the same 2003 interview, Hejlsberg estimated that well-written code has about ten try/finally blocks for every try/catch. Most exception-handling code isn’t about catching at all. It’s about cleaning up.

C# had a shortcut for that from day one. The using statement calls Dispose even when an exception is thrown, because it expands to roughly this:

StreamReader reader = new StreamReader(path);
try
{
    return Settings.Parse(reader.ReadToEnd());
}
finally
{
    if (reader != null)
    {
        ((IDisposable)reader).Dispose();
    }
}

The price was a block. Everything that used the resource had to live inside the using statement’s braces, and each extra resource added another one. C# 8 (2019) added using declarations, which dispose at the end of the enclosing scope, in reverse order:

using var stream = File.OpenRead(path);
using var reader = new StreamReader(stream);
return Settings.Parse(reader.ReadToEnd());

No braces, and no extra indentation. C# 8 also added await using, for resources whose cleanup is itself asynchronous. A StreamWriter has to flush its buffer when it’s disposed, and await using lets that happen without blocking a thread:

public async Task SaveSettingsAsync(string path, Settings settings)
{
    await using var writer = new StreamWriter(path);
    await writer.WriteAsync(settings.ToText());
}

All three together

Put the rewrites together, and here is the same method as you’d write it today:

public Settings LoadSettings(string path)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(path);

    try
    {
        using var reader = new StreamReader(path);
        return Settings.Parse(reader.ReadToEnd());
    }
    catch (IOException ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
    {
        return Settings.Default;
    }
}

Twenty-seven lines became fourteen. The guard is one line, the cleanup has no braces, and the two identical handlers are one.

Look closer, though, and the shape hasn’t changed. It’s still try, catch and a finally hidden inside using, the same model C# 1.0 shipped in 2002. Twenty-four years of releases have trimmed the ceremony around it without touching the model. C# 15 is the first release to build a different one into the language.

return: or don’t throw at all

For one common case, the class library has offered a non-throwing route for two decades. int.TryParse, added in .NET 2.0 (2005), returns false instead of throwing and hands the result back through an out parameter. C# 7 removed the declaration that used to sit on the line above:

if (int.TryParse(text, out var port))
{
    Connect(port);
}

The first post ended with C# 15’s union types, and so does this one, from a different direction. C# 15 is due with .NET 11 in November. A union is a value that is exactly one of a fixed list of types, so a method can return either its result or its failure, and the signature says which:

public union LoadResult(Settings, IOException);

public LoadResult LoadSettings(string path)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(path);

    try
    {
        using var reader = new StreamReader(path);
        return Settings.Parse(reader.ReadToEnd());
    }
    catch (IOException ex)
    {
        return ex;
    }
}

The caller can’t use a LoadResult as Settings until it has checked which case it got, and the compiler warns when a switch misses one:

Settings settings = LoadSettings(path) switch
{
    Settings loaded => loaded,
    IOException => Settings.Default,   // the caller decides what a failure means
};

Now put that signature next to Java’s:

Settings loadSettings(String path) throws IOException

The failure is part of the signature again. Add a case next year, say a FormatException for files that don’t parse, and every switch over LoadResult without a catch-all arm gets a warning. That’s Hejlsberg’s versioning problem from 2003, back in a new shape. The difference is that it’s opt-in, one method at a time, and it’s a warning rather than an error.

In 2003, Hejlsberg said C# would stay neutral on checked exceptions until a better solution turned up. Unions aren’t checked exceptions. But twenty-three years later, C# lets a method put its failures in its signature, if its author decides that’s worth it. When to throw and when to return is a question for its own post.

At a glance

VersionYearAdded
C# 12002try/catch/finally, throw;, using, and no checked exceptions
.NET 2.02005int.TryParse
.NET 42010Task and AggregateException
C# 52012await rethrows the original exception
C# 62015Exception filters (when), await in catch and finally, nameof
C# 72017Throw expressions and out var
C# 82019using declarations and await using
C# 92020or patterns, handy in filters
C# 102021[CallerArgumentExpression], behind the ThrowIf helpers
.NET 82023ThrowIfNullOrWhiteSpace, ThrowIfNegativeOrZero and friends
C# 152026Union types

Written with AI assistance.


Categorized in:

Development,