Skip to main content

std::expected: Error Handling in C++23

 The Problem We're Actually Solving

Let's start before the code. Imagine you write a function that divides two numbers. Easy, right? Except... what happens if someone tries to divide by zero? Your function needs a way to say "hey, something went wrong here" without crashing the whole program or lying about the result.

For decades, C++ programmers have had a few messy options:

  1. Throw an exception — works, but exceptions are expensive, and some codebases (game engines, embedded systems) avoid them entirely.
  2. Return an error code — cheap, but easy to ignore. Nobody checks return codes reliably, and you lose the "why" behind the failure.
  3. Use an output parameter — pass a pointer or reference to fill in with an error. Clunky and easy to mess up.
  4. Return a std::optional — tells you something failed, but not what or why.

C++23 gives us a much cleaner tool: std::expected. Think of it as a box that either contains your successful result, or contains the reason it failed. Never both. Never neither.

The Simplest Way to Think About It

Picture a vending machine. You put in your money and press a button. Two things can happen:

  • It works: you get your snack. 🍫
  • It fails: it doesn't just give you nothing — it tells you why ("out of stock", "insert more coins", etc).

std::expected<T, E> is that vending machine in code form:

  • T = the type of the "snack" (your successful value)
  • E = the type of the "reason it failed" (your error)

That's genuinely the whole concept. Everything else is just syntax.

Setting It Up

You need a C++23-compliant compiler (GCC 12+, Clang 16+, or MSVC with /std:c++latest, roughly speaking — always check your compiler's actual support table since this is a newer feature).

#include <expected>
#include <iostream>
#include <string>

Example 1: The Classic Divide-by-Zero

Let's build that division function.

#include <expected>
#include <iostream>
#include <string>

// This function either returns a double (success)
// or a string explaining what went wrong (failure)
std::expected<double, std::string> divide(double a, double b) {
    if (b == 0.0) {
        return std::unexpected("Cannot divide by zero, buddy.");
    }
    return a / b; // this becomes the "success" value automatically
}

int main() {
    auto result = divide(10.0, 2.0);

    if (result.has_value()) {
        std::cout << "Success! Result: " << result.value() << "\n";
    } else {
        std::cout << "Oops! Error: " << result.error() << "\n";
    }

    auto badResult = divide(10.0, 0.0);

    if (badResult) { // has_value() has a shorthand: just use it like a bool
        std::cout << "Success! Result: " << badResult.value() << "\n";
    } else {
        std::cout << "Oops! Error: " << badResult.error() << "\n";
    }
}

Output:

Success! Result: 5
Oops! Error: Cannot divide by zero, buddy.

Let's slow down and translate that code into English

  • std::expected<double, std::string> — "this function will either give you back a double, or a std::string explaining the problem."
  • return std::unexpected("...") — this is how you say "nope, it failed, here's why." You must wrap your error in std::unexpected(...) — it's the tag that tells std::expected "this is the failure branch, not the success branch."
  • return a / b; — no wrapping needed here. If it's a valid value of type T, std::expected figures out it's the success case automatically.
  • result.has_value() — asks the box "did it work?"
  • if (result) — literally the same thing as has_value(), just shorter. std::expected can be used directly as a boolean condition.
  • result.value() — "give me what's inside, assuming it worked."
  • result.error() — "give me the failure reason, assuming it didn't work."

That's genuinely 90% of what you need to know.

Example 2: Chaining Operations (Where std::expected Really Shines)

Here's where things get fun. Imagine you're parsing user input, then converting it, then doing math on it — and any step could fail. Instead of nesting a pile of if-statements, std::expected lets you chain operations, kind of like std::optional does with and_then.

#include <expected>
#include <iostream>
#include <string>
#include <charconv>

// Step 1: try to convert a string to an integer
std::expected<int, std::string> parseNumber(const std::string& text) {
    int value{};
    auto result = std::from_chars(text.data(), text.data() + text.size(), value);

    if (result.ec == std::errc()) {
        return value;
    }
    return std::unexpected("'" + text + "' is not a valid number.");
}

// Step 2: make sure the number is positive
std::expected<int, std::string> requirePositive(int value) {
    if (value <= 0) {
        return std::unexpected("Number must be positive.");
    }
    return value;
}

// Step 3: square it
std::expected<int, std::string> square(int value) {
    return value * value;
}

int main() {
    std::string input = "6";

    auto finalResult = parseNumber(input)
        .and_then(requirePositive)
        .and_then(square);

    if (finalResult) {
        std::cout << "Final result: " << *finalResult << "\n";
    } else {
        std::cout << "Something broke: " << finalResult.error() << "\n";
    }
}

Output:

Final result: 36

What just happened here (plain English version)

Think of .and_then(...) like a relay race. Each runner (function) only runs if the previous runner successfully passed the baton. The moment someone drops the baton (returns an error), the whole race stops immediately, and that error gets carried straight to the finish line — no need to manually check "did it fail? did it fail? did it fail?" after every single step.

If you change input to "-5", the chain stops after requirePositive and square never even runs. Try it — it's kind of satisfying to watch it short-circuit.

Also notice: *finalResult works too — the * (dereference) operator is a shortcut for .value(), same idea as std::optional.

Example 3: A Custom Error Type (Not Just Strings)

Strings are fine for small examples, but in real projects you usually want a proper error type — often an enum class — so callers can check what kind of error happened, not just read a message.

#include <expected>
#include <iostream>

enum class ParseError {
    Empty,
    NotANumber,
    TooLarge
};

// Turning the enum into a readable message, for when we DO want to print something
std::string describe(ParseError err) {
    switch (err) {
        case ParseError::Empty:      return "The input was empty.";
        case ParseError::NotANumber: return "That's not a number.";
        case ParseError::TooLarge:   return "That number is too big.";
    }
    return "Unknown error.";
}

std::expected<int, ParseError> parseAge(const std::string& text) {
    if (text.empty()) {
        return std::unexpected(ParseError::Empty);
    }
    if (!std::all_of(text.begin(), text.end(), ::isdigit)) {
        return std::unexpected(ParseError::NotANumber);
    }

    int age = std::stoi(text);
    if (age > 150) {
        return std::unexpected(ParseError::TooLarge);
    }
    return age;
}

int main() {
    for (const auto& input : {"25", "", "abc", "999"}) {
        auto result = parseAge(input);
        if (result) {
            std::cout << "Valid age: " << *result << "\n";
        } else {
            std::cout << "Invalid (" << input << "): " << describe(result.error()) << "\n";
        }
    }
}

Output:

Valid age: 25
Invalid (): The input was empty.
Invalid (abc): That's not a number.
Invalid (999): That number is too big.

Why is this better than a string? Because now, calling code can actually branch on the error type — like showing a different UI message for "empty" versus "too large" — instead of doing fragile string comparisons.

The Handy Extra Tools

std::expected comes with a small toolbox of convenience methods worth knowing:

Method What it does in plain terms
.value_or(fallback) "Give me the value, or if it failed, just use this fallback instead."
.and_then(func) "If it worked, pass the value into the next function."
.or_else(func) "If it failed, let me handle/recover from the error."
.transform(func) "If it worked, transform the value into something else."
.transform_error(func) "If it failed, transform the error into something else."

Quick taste of value_or:

auto result = divide(10.0, 0.0);
double safeValue = result.value_or(0.0); // no error handling needed, just a fallback
std::cout << safeValue << "\n"; // prints 0

Why Not Just Use Exceptions?

Good question — exceptions still have their place. But std::expected gives you a few things exceptions don't:

  • It's visible in the function signature. You can see right there in the return type that this function might fail — no digging through documentation or try/catch guessing games.
  • The compiler forces you to think about it. You can't accidentally use the value without at least acknowledging there's an error branch (well — you can ignore it, but it's much more obvious when you do).
  • No stack unwinding cost. Exceptions have runtime overhead when thrown; std::expected is just a regular return value, so it's typically cheaper and more predictable — useful for performance-sensitive code like games or real-time systems.
  • Errors are just data. You can store them, log them, pass them around, and inspect them like any normal value.

The tradeoff: it does add a little verbosity, and for truly catastrophic, unrecoverable failures (like memory corruption), exceptions or aborting are usually still the better tool.

The One-Paragraph Summary

std::expected<T, E> is a box that holds either a successful value of type T, or an error of type E — never both. You build a success case just by returning a value normally, and a failure case by wrapping it in std::unexpected(...). You check which one you got with has_value() or by treating it like a boolean, unwrap the value with .value() or *, and grab the error with .error(). Chain multiple fallible steps together with .and_then() so the first failure short-circuits everything after it. It's basically a safer, more expressive return code — one that forces you to actually deal with failure instead of quietly ignoring it.

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...