Effective Error Handling with C++ std::error_code

2025-09-24

The assignment operator for std::error_code seems simple, but it's easy to misuse, especially when you're not paying close attention to what's being assigned. The operator essentially replaces the current error code with a new one.

A common mistake is assigning a new error code but then not checking the new state before proceeding. This can lead to bugs where you're still acting on the old, potentially successful, state.

Problematic Code

#include <system_error>
#include <iostream>

void do_something_risky(std::error_code& ec) {
    // A function that might set the error code
    // Let's simulate a failure
    ec = std::make_error_code(std::errc::address_family_not_supported);
    // You might forget to check ec here
}

int main() {
    std::error_code my_error_code;
    do_something_risky(my_error_code);

    // Incorrectly continues without checking the new value
    if (!my_error_code) { // This check should be made AFTER the function call
        std::cout << "Operation succeeded, but it actually failed!" << std::endl;
    }
    return 0;
}

In this example, the if statement is in the wrong place. The code in main should check my_error_code after do_something_risky has been called.

Corrected Code

#include <system_error>
#include <iostream>

void do_something_risky(std::error_code& ec) {
    // Set the error code if something goes wrong
    ec = std::make_error_code(std::errc::address_family_not_supported);
}

int main() {
    std::error_code my_error_code;
    do_something_risky(my_error_code);

    // Correctly check the error code after the assignment
    if (my_error_code) {
        std::cout << "Operation failed: " << my_error_code.message() << std::endl;
    } else {
        std::cout << "Operation succeeded!" << std::endl;
    }
    return 0;
}

This is a much safer way to handle error codes. By checking the value of my_error_code after the function call, you ensure your program's flow is based on the most current information.

While the assignment operator is straightforward, modern C++ offers more robust and expressive ways to handle errors. These alternatives can often lead to cleaner, more readable, and safer code.

Instead of using an output parameter for an error code, you can use a return type that represents either a successful value or an error. This is a common pattern in many languages and libraries. std::optional is a great choice if the "success" state has no value, but a more general "Result" type is even better.

The "Result" Type Pattern This pattern involves creating a struct or class that can hold either a value or an error. Libraries like tl::expected or boost::outcome implement this, and it's a very popular pattern in C++.

Sample Code with a Simple Result-like Type

#include <system_error>
#include <iostream>
#include <variant>
#include <string>

// A simple result type that holds either an integer or an error_code
using Result = std::variant<int, std::error_code>;

Result do_something_and_return_result() {
    // Let's simulate a success
    // return 42; 

    // Or a failure
    return std::make_error_code(std::errc::address_family_not_supported);
}

int main() {
    Result res = do_something_and_return_result();

    if (std::holds_alternative<int>(res)) {
        int value = std::get<int>(res);
        std::cout << "Operation succeeded with value: " << value << std::endl;
    } else {
        std::error_code ec = std::get<std::error_code>(res);
        std::cout << "Operation failed: " << ec.message() << std::endl;
    }

    return 0;
}

This approach forces you to explicitly handle both the success and failure cases, which can prevent you from accidentally forgetting to check the error state. It's often called "error-handling by return value," and it's a great pattern to adopt.

Even with these alternatives, using std::error_code via an output parameter is still a valid and common pattern, especially in older codebases or APIs that need to be compatible with C style functions.

When it works well

Legacy APIs
When you are wrapping a C-style API that uses an integer return code and an output parameter for the error state.

Performance-critical code
In some cases, avoiding exceptions can be beneficial for performance, and std::error_code is a good way to achieve this.


cpp



The Dangers of std::expected::operator* and How to Avoid Them

The std::expected class is part of the C++23 standard library and is designed to represent a value that might contain either a valid result of type T or an error of type E. Think of it as a modern


Avoid Threading Headaches: Understanding std::jthread's stop_token

One of the most common issues with get_stop_token is trying to use it after the jthread has been joined or has gone out of scope


From Exchange to Mutex: A C++ Concurrency Toolkit

std::atomic_ref::exchange is a member function of the std::atomic_ref class template. It performs an atomic read-modify-write operation



Understanding and Using std::forward_as_tuple in C++

std::forward_as_tuple is a function template in the C++ standard library. It's used to create a tuple of references. The "forwarding" part means it preserves the value category (lvalue or rvalue) of the arguments you pass to it


C++ std::filesystem::is_directory: Common Issues and Alternatives

std::filesystem::is_directory is a C++17 function that checks if a given path points to a directory. It's super handy for tasks like recursively traversing a folder or organizing files


C++ Smart Pointers: When to Use std::unique_ptr::reset and When to Avoid It

std::unique_ptr::reset is a function that changes the managed pointer held by a std::unique_ptr. It's a way to eitherRelease the current object and set the pointer to a new one


C++ Standard Headers: The climits Guide to Integer Limits

A frequent mistake is using the wrong limit for a specific data type. For example, using INT_MAX to check the bounds of a long long variable


Why Not Use std::valarray? Exploring Alternatives for Numerical Swapping in C++

The non-member function std::swap for std::valarray is a specialized version of the standard std::swap algorithm. Its purpose is simple to efficiently exchange the contents of two std::valarray objects of the same type and size


tag code block, as you requested.

The member function std::valarray::size() simply returns the number of elements currently stored in the std::valarray object


Mastering std::deque::operator= in C++: Tips, Tricks, and Code Examples

The operator= for std::deque is used to assign new contents to a deque, replacing its existing contents. Think of it like giving a deque a completely new set of data