Skip to content

Designing with Exceptions

The Course
•
30 min study

The beginner course showed try and catch. Writing them well is really about three questions: which failures can happen, who can do something about them, and what state is left behind.

Catch what you can handle

An exception travels up the call stack until a matching catch. Catch specific types, at a point where you can respond sensibly. A bare catch (Exception) that hides everything also hides your own bugs, so that a NullReferenceException reads the same as bad input.

Which catch runs? C#
foreach (string input in new[] { "5", "zero", "0" })
{
    try
    {
        Console.WriteLine(100 / int.Parse(input));
    }
    catch (FormatException)
    {
        Console.WriteLine("not a number");
    }
    catch (DivideByZeroException)
    {
        Console.WriteLine("can't divide by zero");
    }
}
Check your prediction
Text
20
not a number
can't divide by zero

Order matters as well. A catch for a base type before a derived type is a compile error, because the second could never run.

finally always runs

Code in finally runs whether the try succeeded, threw an exception or returned. That's the place to restore state. The next example's Depth must return to 0 whatever happens. On Day 5, using will do this for you with files.

Cleanup on every path C#
var tracker = new Tracker();

Console.WriteLine(tracker.Run(() => 1));

try
{
    tracker.Run<int>(() => throw new InvalidOperationException("boom"));
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}
Console.WriteLine(tracker.Depth);

class Tracker
{
    public int Depth { get; private set; }

    public T Run<T>(Func<T> action)
    {
        Depth++;
        try
        {
            return action();
        }
        finally
        {
            Depth--;
            Console.WriteLine("cleaned up");
        }
    }
}
Check your prediction
Text
cleaned up
1
cleaned up
boom
0

Your own exception types

A custom exception gives callers something specific to catch and can carry details. Derive from Exception, and pass on a message. Pass the original failure as inner so nothing is lost when one exception wraps another.

Wrapping a low-level failure C#
try
{
    LoadAge("not json");
}
catch (ConfigException e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine(e.Key);
    Console.WriteLine(e.InnerException?.GetType().Name);
}

static int LoadAge(string text)
{
    try
    {
        return int.Parse(text);
    }
    catch (FormatException e)
    {
        throw new ConfigException("age", $"age is not a number: {text}", e);
    }
}

class ConfigException : Exception
{
    public string Key { get; }

    public ConfigException(string key, string message, Exception inner) : base(message, inner)
    {
        Key = key;
    }
}
Check your prediction
Text
age is not a number: not json
age
FormatException

Callers now depend on ConfigException, not on how the value happens to be parsed. The tracker's StoreFormatException works this way.

throw; keeps the trail

Inside a catch, a bare throw; lets the same exception continue, with its original stack trace. throw e; resets the trace, so don't use that form. A when filter catches only in some cases, and leaves the rest alone.

Log and pass it on C#
try
{
    Process(-1);
}
catch (ArgumentException e)
{
    Console.WriteLine($"caller saw: {e.Message}");
}

Console.WriteLine(Safe(0));

static void Process(int value)
{
    try
    {
        if (value < 0)
        {
            throw new ArgumentException("negative");
        }
    }
    catch (ArgumentException)
    {
        Console.WriteLine("logged");
        throw;
    }
}

static string Safe(int value)
{
    try
    {
        return (10 / value).ToString();
    }
    catch (DivideByZeroException) when (value == 0)
    {
        return "n/a";
    }
}
Check your prediction
Text
logged
caller saw: negative
n/a

When not to throw

Exceptions are for situations a method can't handle and didn't expect. If failure is normal, as it is with user input, return a result that says so: TryParse does this rather than throwing. Exceptions are also slow compared with a return. The next lesson builds this idea into a type.

Fix it: A catch that can never run

This tries to give a friendly message for bad numbers. Run it and read the error.

A catch that can never run C#
try
{
    int port = int.Parse("abc");
    Console.WriteLine(port);
}
catch (Exception)
{
    Console.WriteLine("something went wrong");
}
catch (FormatException)
{
    Console.WriteLine("not a number");
}
Check your prediction
Text
error CS0160
A previous catch clause already catches all exceptions of this or of a super type ('Exception')

catch clauses are tried from top to bottom, and the first match wins. FormatException is a kind of Exception, so the first clause would always take it, and the compiler refuses to keep a clause that can't run. Fix the order.

Fix it

Put the specific type first and the general one last:

C#
try
{
    int port = int.Parse("abc");
    Console.WriteLine(port);
}
catch (FormatException)
{
    Console.WriteLine("not a number");
}
catch (Exception)
{
    Console.WriteLine("something went wrong");
}
Text
not a number

Better still, ask whether you can handle every exception here at all. As this lesson says, catch only what you can do something useful about, and let the rest travel up.

Your turn

Exercise

A settings loader

Write Settings.Load(string text), for text such as port=80. It returns the port number. Create SettingsException with a property Line, holding the text that caused the problem. Throw it, with the message expected port=number, if the text doesn't start with port= or the number doesn't parse. If the port is outside 1 to 65535, throw it with port out of range.

Print the port for port=80, and print the message and Line for host=x, port=abc and port=70000.

When it works, it prints:

Text
80
expected port=number: host=x
expected port=number: port=abc
port out of range: port=70000
Your workspace C#
foreach (string text in new[] { "port=80", "host=x", "port=abc", "port=70000" })
{
    Console.WriteLine(text);
}
Hint 1: the idea

Validate in order, and throw one exception type for every problem. The caller only needs one catch.

Hint 2: a first step

Write the exception class first. text.StartsWith and text[5..] take care of the prefix, and int.TryParse means you never need to catch FormatException.

Show one solution
C#
foreach (string text in new[] { "port=80", "host=x", "port=abc", "port=70000" })
{
    try
    {
        Console.WriteLine(Settings.Load(text));
    }
    catch (SettingsException e)
    {
        Console.WriteLine($"{e.Message}: {e.Line}");
    }
}

static class Settings
{
    public static int Load(string text)
    {
        if (!text.StartsWith("port=") || !int.TryParse(text[5..], out int port))
        {
            throw new SettingsException(text, "expected port=number");
        }
        if (port < 1 || port > 65535)
        {
            throw new SettingsException(text, "port out of range");
        }
        return port;
    }
}

class SettingsException : Exception
{
    public string Line { get; }

    public SettingsException(string line, string message) : base(message)
    {
        Line = line;
    }
}
Text
80
expected port=number: host=x
expected port=number: port=abc
port out of range: port=70000

SettingsException carries the offending line as a property, so the caller can report it without parsing the message. The loader checks the format before the range, so each failure gets the most useful explanation. Only SettingsException is caught: a bug elsewhere, such as a NullReferenceException, would still surface instead of being reported as a settings problem.

Was this article helpful?

Your response is saved on this device.