C++ Error Handling: A Guide to std::error_code::category

2025-09-08

When working with std::error_code, a couple of common issues can trip you up.

A frequent problem is trying to compare std::error_code objects from different categories directly. For example, a filesystem error and a networking error might have the same integer value, but they mean completely different things. The wrong way to do it

#include <iostream>
#include <system_error>
#include <fstream>

int main() {
    std::error_code ec_fs; // Filesystem error
    std::error_code ec_net; // Network error
    
    // This is problematic! Both might have a value of 2, but they are not the same kind of error.
    // The meaning of '2' depends on the category.
    if (ec_fs == ec_net) { 
        std::cout << "This comparison is misleading!" << std::endl;
    }
    
    return 0;
}

The right way to do it
To avoid this, you should always compare the error code's category first, or compare against specific, named std::errc or std::io_errc constants which are category-aware.

#include <iostream>
#include <system_error>
#include <fstream>

int main() {
    std::error_code ec_fs = std::make_error_code(std::errc::bad_address);
    std::error_code ec_net = std::make_error_code(std::errc::bad_address);

    // This is still not great, but at least you know you're comparing the *same type* of error.
    if (ec_fs.category() == ec_net.category() && ec_fs.value() == ec_net.value()) {
        std::cout << "The error codes are the same." << std::endl;
    }
    
    // The best way is to check against a specific error constant.
    if (ec_fs == std::errc::bad_address) {
        std::cout << "Filesystem error: Bad address." << std::endl;
    }
    
    return 0;
}

While std::error_code is a solid choice, especially for low-level system errors, there are other ways to handle errors in C++.

For logic errors and situations where a function cannot proceed, throwing an exception is often the most idiomatic and clear solution in modern C++. It's perfect for when an error is truly exceptional and not part of the normal program flow. Example

#include <iostream>
#include <stdexcept>

double divide(double numerator, double denominator) {
    if (denominator == 0) {
        throw std::invalid_argument("Cannot divide by zero!");
    }
    return numerator / denominator;
}

int main() {
    try {
        double result = divide(10.0, 0.0);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}

When to use it
Use exceptions for things that are unexpected and prevent the function from completing its job, like passing a null pointer to a function that requires a valid one.

This is a great, lightweight option for functions that might fail to produce a result. Instead of returning an error code or throwing an exception, you return an object that either has a value or doesn't. Example

#include <iostream>
#include <optional>

std::optional<int> find_item(const std::vector<int>& items, int target) {
    for (int i = 0; i < items.size(); ++i) {
        if (items[i] == target) {
            return i; // Return the index wrapped in std::optional
        }
    }
    return std::nullopt; // Return an empty optional if not found
}

int main() {
    std::vector<int> numbers = {10, 20, 30};
    if (auto result = find_item(numbers, 20)) {
        std::cout << "Found at index: " << *result << std::endl;
    } else {
        std::cout << "Item not found." << std::endl;
    }
    return 0;
}

When to use it
Use std::optional when a function's failure is just a matter of "no result available," not a critical error. For example, find functions or parsers.


cpp



C++ Metaprogramming: Comparing Ratios at Compile Time

First off, std::ratio_not_equal is a compile-time type trait used for comparing two std::ratio types. It's defined in the <ratio> header


Understanding std::nouppercase in C++: Sticky Flags and How to Fix Them

std::nouppercase is a manipulator used with C++ streams to ensure that uppercase letters are not used when writing numbers to a stream in hexadecimal or scientific notation


Mastering Multibyte Characters in C++: A Guide to Replacing std::mblen

One of the most common issues with std::mblen is that it's highly dependent on the current locale. This means its behavior can change depending on the user's system settings



C++ Compile-Time Assertions: Understanding static_assert and its Predecessors

One of the most common issues developers face with static_assert is using a non-constant expression as the condition. static_assert can only evaluate expressions that are known at compile time


Troubleshooting C++ std::basic_filebuf::seekoff()

It's a versatile function, but it can sometimes be tricky to use, especially if you're not familiar with file handling in C++. Here's a look at some common pitfalls and how you can work around them


The C++ #define Directive: Common Pitfalls and Modern Alternatives

A #define directive is a preprocessor command in C and C++. It's used to create a macro, which is essentially a symbolic name or constant that the preprocessor replaces with a specified value or code snippet before the compilation process begins


C++ Concurrency: std::shared_mutex Explained

The std::shared_mutex class in C++ is a great tool for managing concurrent access to shared data. It allows multiple threads to read data at the same time


Title: A Guide to va_copy and Safer Variadic Functions in C++

First, let's quickly review what va_copy does. In C++, you can create functions that accept a variable number of arguments


Manual Formatting vs. the date Library for C++ Chrono

The biggest problem you'll run into with std::chrono::operator<<(std::chrono::year_month) is that it wasn't standardized until C++20


C++ cassert: Common Pitfalls and Alternatives

The assert() macro is a debugging feature that checks a condition. If the condition you provide is true, the program continues as normal