C++ Concurrency: Handling std::future_errc with std::make_error_code

2025-09-06

A very common mistake is simply forgetting to include the necessary header file. This will lead to a compilation error.

Wrong way

#include <iostream>
#include <future>

int main() {
    std::future<int> f;
    auto ec = std::make_error_code(std::future_errc::no_state); // Error!
    return 0;
}

Correct way

You need to include <system_error>. This header contains the definitions for std::error_code, std::error_condition, and std::make_error_code.

Corrected code

#include <iostream>
#include <future>
#include <system_error> // Don't forget this!

int main() {
    std::future<int> f;
    auto ec = std::make_error_code(std::future_errc::no_state);
    std::cout << "Error code: " << ec.message() << std::endl;
    return 0;
}

This is a simple but crucial step. Without it, the compiler doesn't know what std::make_error_code is.

Sometimes people get confused about what each std::future_errc value means and when to use them.

broken_promise
This happens when a std::future object's shared state is "abandoned" without setting a value. For example, if the std::promise goes out of scope and is destroyed before a value is set.

future_already_retrieved
This occurs if you try to call std::future::get() or std::future::share() more than once on the same std::future object.

no_state
This is the error you get if you try to use a std::future that doesn't have any shared state associated with it, like a default-constructed one.

promise_already_satisfied
This happens if you try to set a value or an exception on a std::promise that has already had its value set.

Example of the wrong usage

#include <iostream>
#include <future>
#include <system_error>

int main() {
    std::promise<int> p;
    p.set_value(10);
    try {
        p.set_value(20); // This will throw an exception
    } catch (const std::future_error& e) {
        // You might check for this:
        if (e.code() == std::future_errc::broken_promise) {
            std::cout << "Wrong! This is not the right error code." << std::endl;
        }
    }
    return 0;
}

Correct way

You should check against the appropriate enum value. In this case, it's promise_already_satisfied.

Corrected code

#include <iostream>
#include <future>
#include <system_error>

int main() {
    std::promise<int> p;
    p.set_value(10);
    try {
        p.set_value(20);
    } catch (const std::future_error& e) {
        // The error code will be std::future_errc::promise_already_satisfied
        if (e.code() == std::make_error_code(std::future_errc::promise_already_satisfied)) {
            std::cout << "Caught the correct error: " << e.what() << std::endl;
        }
    }
    return 0;
}

The most common and often best way to handle these errors is by catching the std::future_error exception directly. The std::make_error_code function is more useful when you're working with functions that return std::error_code instead of throwing exceptions, but for many standard library concurrency functions, try...catch is the way to go.

Example code

#include <iostream>
#include <future>
#include <thread>
#include <system_error>

void do_something_async(std::promise<int>& p) {
    // We intentionally don't set a value here to cause a broken_promise error
    // The promise will be destroyed when the function exits.
    std::cout << "Async task started..." << std::endl;
    // ... some work that never finishes or sets a value
}

int main() {
    std::promise<int> p;
    std::future<int> f = p.get_future();
    std::thread t(do_something_async, std::ref(p));

    try {
        // The thread will finish, and the promise will be destroyed,
        // which will cause a broken_promise error when we call get()
        t.join(); 
        int value = f.get(); 
        std::cout << "Result: " << value << std::endl;
    } catch (const std::future_error& e) {
        std::error_code ec = e.code();
        std::cout << "Caught a std::future_error: " << e.what() << std::endl;
        if (ec == std::make_error_code(std::future_errc::broken_promise)) {
            std::cout << "The promise was broken! This is the expected error." << std::endl;
        } else {
            std::cout << "Unexpected error code: " << ec.message() << std::endl;
        }
    }

    return 0;
}

This example shows how to catch the exception and then use std::make_error_code to compare the error_code from the exception against a known value. This is a very robust way to handle these kinds of errors.

Some C++ APIs, especially those that need to be "no-except" or used in environments where exceptions are not ideal, might return std::error_code instead of throwing. In such a case, std::make_error_code becomes incredibly useful for creating the error object to return.

Example code (hypothetical API)

#include <iostream>
#include <future>
#include <system_error>

std::error_code retrieve_value_from_future(std::future<int>& f, int& out_value) noexcept {
    if (!f.valid()) {
        return std::make_error_code(std::future_errc::no_state);
    }
    try {
        out_value = f.get();
        return std::error_code(); // Success! Return a default-constructed, empty error_code
    } catch (const std::future_error& e) {
        return e.code();
    }
}

int main() {
    std::future<int> f_no_state;
    int result = 0;
    
    std::error_code ec = retrieve_value_from_future(f_no_state, result);

    if (ec) { // Check if the error_code is not empty (i.e., an error occurred)
        std::cout << "Error occurred: " << ec.message() << std::endl;
    } else {
        std::cout << "Value retrieved: " << result << std::endl;
    }

    return 0;
}

cpp



A Friendly Guide to C++ Signal Handling with

The <csignal> header provides functions for handling signals in your C++ programs. A signal is a way for an operating system to notify a running program about an event


Mastering explicit in C++: A Guide to Avoiding Constructor Pitfalls

The main purpose of the explicit specifier is to prevent a constructor from being used for implicit conversions. This is especially useful for single-argument constructors and conversion operators


A Developer's Guide to C++ std::char_traits::assign and Safer Alternatives

Hey there! Let's dive into std::char_traits::assign for C++ strings. It's a pretty low-level function, and while you might not use it directly very often



From Global State to Safe Streams: A New Approach to C++ Localization

std::setlocale is a function in the C++ Standard Library, inherited from C, that's used to set or query the program's locale


Common Mistakes with std::ranges::back() and How to Fix Them

This design choice prevents common issues and ensures that the library's concepts are upheld. For example, a std::views::filter would not know how to efficiently find the last element because it would need to iterate through the entire underlying range


The C++ Scoped Allocator Conundrum: A Guide to Deduction Guides and CTAD

The main issue arises when you try to use class template argument deduction (CTAD) with std::scoped_allocator_adaptor and a container


Mastering C++ Concepts: std::convertible_to Pitfalls and Alternatives

Here is a friendly, detailed explanation of common pitfalls and alternative solutions with code examples.The concept std::convertible_to<From


C++ Thread Synchronization: Troubleshooting wait_until with Code Examples

Hey there! Let's talk about std::condition_variable_any::wait_until in C++. This is a really useful tool for managing threads


C++ Regex Iterators: Fixing std::regex_iterator Constructor Errors

First, let's quickly review what std::regex_iterator does. It's a C++ standard library class that iterates over all non-overlapping matches of a regular expression within a sequence of characters (like a string)


std::mdspan: Pitfalls of Operator= and Deep Copy Alternatives

std::mdspan::operator= is used to assign one mdspan to another. This is essentially a "re-binding" operation. It's crucial to understand that it does not copy the data that the mdspan views