I'll Be Backend
Principles · C++

Error handling: replace error codes with exceptions

Let failures reach the code that can handle them, without every caller checking.

11 steps4 chapters~5 min at 1.25×#error handling#exceptions#error codes#std::runtime_error
Language
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the C++ video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–4

Refactor

Steps 5–7

Payoff

Steps 8–9

Recap

Steps 10–11

The code: before and after

Before

struct Wallet {
    static constexpr int OK = 0, NO_ACCOUNT = -1, LOW_BALANCE = -2;
    std::map<std::string, int> balances;

    int withdraw(const std::string& id, int amount) {
        auto it = balances.find(id);
        if (it == balances.end()) return NO_ACCOUNT;
        if (it->second < amount) return LOW_BALANCE;
        it->second -= amount;
        return OK;
    }

    int transfer(const std::string& from, const std::string& to,
                 int amount) {
        if (!balances.contains(to)) return NO_ACCOUNT;
        int code = withdraw(from, amount);
        if (code != OK) return code;
        balances[to] += amount;
        return OK;
    }
};

struct TransferHandler {
    std::string handle(Wallet& wallet, const std::string& from,
                       const std::string& to, int amount) {
        int code = wallet.transfer(from, to, amount);
        if (code == Wallet::NO_ACCOUNT) return "404 no such account";
        if (code == Wallet::LOW_BALANCE) return "409 balance too low";
        return "200 ok";
    }
};

After

struct AccountNotFoundException : std::runtime_error {
    using runtime_error::runtime_error;
};
struct InsufficientFundsException : std::runtime_error {
    using runtime_error::runtime_error;
};
struct AccountFrozenException : std::runtime_error {
    using runtime_error::runtime_error;
};

struct Wallet {
    std::map<std::string, int> balances;
    std::set<std::string> frozen;

    void freeze(const std::string& id) { frozen.insert(id); }

    void withdraw(const std::string& id, int amount) {
        auto it = balances.find(id);
        if (it == balances.end()) throw AccountNotFoundException(id);
        if (frozen.contains(id)) throw AccountFrozenException(id);
        if (it->second < amount) throw InsufficientFundsException(id);
        it->second -= amount;
    }

    void transfer(const std::string& from, const std::string& to,
                  int amount) {
        if (!balances.contains(to)) throw AccountNotFoundException(to);
        withdraw(from, amount);
        balances[to] += amount;
    }
};

struct TransferHandler {
    std::string handle(Wallet& wallet, const std::string& from,
                       const std::string& to, int amount) {
        try {
            wallet.transfer(from, to, amount);
            return "200 ok";
        } catch (const AccountNotFoundException&) {
            return "404 no such account";
        } catch (const InsufficientFundsException&) {
            return "409 balance too low";
        } catch (const AccountFrozenException&) {
            return "423 account frozen";
        }
    }
};

Transcript, step by step

Problem

Step 1: A wallet that returns numbers Before

This wallet keeps balances in whole euros, and it reports trouble with three numbers, OK, no account and low balance. Withdraw returns minus one for an unknown account, minus two when the balance is too low, and zero when the money left. Transfer checks the receiver, calls withdraw, and passes any error code it gets straight back up. The handler is the one caller, and each code ends up as the HTTP-style status text the handler returns, so a missing account becomes four oh four.

Step 2: Freeze accounts Code smell

Compliance now freezes accounts, and a frozen account can't send money. So we add a fourth code, minus three, a set of frozen ids, and a check in withdraw, right after the lookup, that returns it. The handler didn't change, and it compiles fine.

Step 3: Every caller has to check Code smell

An error code is a failure returned as an ordinary number, so every caller up the chain has to remember to check it, and nothing makes them. Withdraw returns the new code here, transfer checks it and passes it up here, the handler compares it with each code it knows here, and anything else falls through to here. So right now, a transfer from a frozen account moves no money, and the handler answers two hundred OK, because nobody added a branch for minus three. Each caller in the chain has to write the line that passes the error code up, and nothing forces it to, while the handler treats any number it doesn't know as success, so one missing branch turns a failure into two hundred OK.

Step 4: Back it out, refactor first Plan

Let's back the freeze out. We'll refactor first, turning each error code into an exception one at a time, and then the freeze goes back in.

Refactor

Step 5: Missing account throws Replace Error Code with Exception

We start with the missing account, and Replace Error Code with Exception gives it a class of its own, Account Not Found Exception. It derives from the standard runtime error and inherits its constructor, so the account id becomes the message. Withdraw throws it here and transfer throws it here, each with the account id, where they used to return minus one. C plus plus has no checked exceptions, so neither signature changes, and transfer's check for minus two still compiles as it was. The handler wraps its call in a try and catches the exception by const reference, the usual C plus plus way. That catch returns the same four oh four status text as before, so the no account constant is gone.

Step 6: Low balance throws Replace Error Code with Exception

Low balance gets the same move, with Insufficient Funds Exception. Withdraw throws it when the balance is too small, and the handler gets a second catch that returns the same four oh nine status text. That leaves withdraw returning OK and nothing else, so the check in transfer can never fire.

Step 7: withdraw and transfer return void Change Function Declaration

Change Function Declaration makes withdraw and transfer return void, since there's no number left worth returning. The OK constant, every return OK, and the line that passed the error code up all go, so transfer is down to three statements. It checks the receiver, takes the money from the sender, and pays the receiver. In the handler, the try holds the transfer call and then two hundred OK, which runs only if transfer came back normally.

Payoff

Step 8: The freeze is one throw, one catch Payoff

Now the freeze goes in again, and it starts with a third exception class, Account Frozen Exception. The wallet gets the frozen set and the freeze method, and withdraw throws the new exception here, after the lookup and before the balance check. The handler gets one more catch, and it answers with four twenty three, account frozen. Transfer didn't change at all, because it has no line that carries a failure up.

Step 9: Why it was easy Payoff

Back at the same four places, withdraw throws here, and transfer has no line here that passes a failure up, so no caller in between can forget one. The handler has one catch here for each failure it reports, and two hundred OK runs here only when transfer returned normally. A forgotten if used to answer two hundred OK in silence, but forget a catch now and the exception leaves handle loudly, so it never reaches that line. This fits here because the failure starts deep in withdraw and only the handler knows what to say about it, so transfer shouldn't have to carry it.

Recap

Step 10: Where we started, where we ended Before / after

On the left, withdraw and transfer return numbers, and transfer has to pass each one up by hand. The handler's checks end in two hundred OK, so any code it doesn't know counts as success. On the right, withdraw and transfer throw, and transfer is three statements with nothing to relay. And the handler's try reaches two hundred OK only when the transfer worked, with a catch for each failure.

Step 11: When to reach for it Takeaways

Reach for it when a failure starts deep in a call chain and only a caller near the top knows how to answer it. Skip it when the direct caller answers the failure, like a lookup that often finds nothing, because with no chain to skip, find and an if do the same job. You'll spot it by constants like minus one, by a line that passes a code up the chain, or by a last branch that treats unknown codes as success. The standard library works this way too, because stoi throws invalid argument for text that isn't a number, while from chars hands back an error code to the caller that answers itself.