In C++, how do std::error_code, std::error_condition and std::error_category fit together, and where does std::system_error come in?
answer
- a value plus a category
- categories compare by address
- specific code, portable condition
- the throwing wrapper
basics
~20 sA std::error_code is an int plus a reference to a std::error_category saying what the int means; a std::error_condition is a portable meaning such as std::errc values. std::system_error is the exception that carries an error_code when the throwing API reports it.
solid answer
~40 s`std::error_code` stores a value and a pointer to an `std::error_category`, a singleton whose identity (its address) says which namespace the value belongs to: `std::system_category()` for OS errors, `std::generic_category()` for POSIX `errno` values, or your own. Two `error_code`s are equal only if both category and value match. To ask "is this a missing file?" portably, compare with a `std::error_condition`, for example `ec == std::errc::no_such_file_or_directory`; the category's `equivalent` and `default_error_condition` decide. `std::system_error` derives from `std::runtime_error` and wraps an `error_code`; APIs such as `std::filesystem` offer a throwing overload that throws an exception derived from it, and a non-throwing overload taking `std::error_code&`. A build tool can define its own category so its errors travel in the same type.
code
cpp · 26 lines#include <cerrno>
#include <filesystem>
#include <iostream>
#include <system_error>
int main() {
std::error_code ec;
auto size = std::filesystem::file_size("missing.o", ec); // no throw: reports through ec
std::cout << "size " << size << ", category " << ec.category().name()
<< ", value " << ec.value() << ", message: " << ec.message() << '\n';
std::error_code sys(ENOENT, std::system_category());
std::error_code gen(ENOENT, std::generic_category());
std::cout << std::boolalpha
<< (sys == gen) << ' ' // false: different categories
<< (sys == std::errc::no_such_file_or_directory) << ' ' // true: condition comparison
<< (gen == std::errc::no_such_file_or_directory) << ' '
<< (ec == std::errc::no_such_file_or_directory) << '\n';
try {
auto n = std::filesystem::file_size("missing.o"); // throwing overload
std::cout << n << '\n';
} catch (const std::system_error& e) { // filesystem_error derives from it
std::cout << "code " << e.code().value() << " (" << e.code().category().name() << "): " << e.what() << '\n';
}
}go deeper
Know that an error_code holds a number plus a category, that if (ec) tests for an error, and that system_error is the exception that carries one.
Explain the difference between comparing two error_codes and comparing an error_code with an errc condition.
Implement a custom category correctly, as a singleton with make_error_code found by ADL and the is_error_code_enum specialization, and use the dual overloads of filesystem.
Decide where the codebase uses error_code versus exceptions, and define one mapping from internal categories to the process exit statuses tools report.
## The pieces in `<system_error>` | Type | What it holds | Purpose | |---|---|---| | `std::error_category` | nothing but behaviour: `name()`, `message(int)`, `default_error_condition(int)`, `equivalent(...)` | says what integer values mean | | `std::error_code` | an `int` value and a pointer to a category | a specific, possibly platform-specific error | | `std::error_condition` | an `int` value and a pointer to a category | a portable meaning to compare against | | `std::errc` | enumerators named after POSIX errors | the standard source of conditions | | `std::system_error` | an `error_code` plus a message | the exception that carries one | ## Categories are singletons compared by address `std::error_category` has a deleted copy constructor and copy assignment, and its `operator==` returns `this == &rhs`. A category is therefore one object per kind of error, and code compares categories by identity. The standard provides two: - `std::generic_category()`, whose `name()` is `"generic"`, for POSIX `errno` values; - `std::system_category()`, whose `name()` is `"system"`, for whatever the operating system reports. Its `default_error_condition` maps a value to a `generic_category()` condition when it corresponds to a POSIX `errno`; what corresponds is unspecified. A default-constructed `error_code` has value `0` and `system_category()`, and its `explicit operator bool` is `false`: no error. ## Comparing codes against conditions The two comparisons behave differently: 1. `error_code == error_code` compares **category and value**. `std::error_code(ENOENT, std::system_category()) == std::error_code(ENOENT, std::generic_category())` is `false` in the snippet below. 2. `error_code == error_condition` asks the categories: it is true if `lhs.category().equivalent(lhs.value(), rhs)` or `rhs.category().equivalent(lhs, rhs.value())`. That is why both of those codes compare equal to `std::errc::no_such_file_or_directory`. `std::errc` is an *error condition* enum, so `ec == std::errc::...` works, but `std::error_code ec = std::errc::permission_denied;` does not compile; clang reports `no viable conversion from 'std::errc' to 'std::error_code'`. Use `std::make_error_code(std::errc::permission_denied)`. Portable code therefore tests `ec == std::errc::...`, never `ec.value() == ENOENT`. ## Throwing and non-throwing overloads `std::filesystem` shows the standard pattern: most functions come in two forms. - `std::filesystem::file_size(p)` throws `std::filesystem::filesystem_error`, derived from `std::system_error`, on failure. - `std::filesystem::file_size(p, ec)` sets `ec` and returns a sentinel instead. The exception's `code()` returns the same `error_code`, so a handler for `const std::system_error&` can still test `e.code() == std::errc::no_such_file_or_directory`. In the libc++ run below, the filesystem error carried `generic_category()` and value 2. `std::system_error`'s constructors guarantee that `code()` equals the code passed in and that `what()` contains the message argument. ## A category for the build tool A command-line build tool can put its own failures in the same type: 1. Define `enum class build_errc { ok = 0, missing_source = 1, compiler_crashed = 2 };`. 2. Derive a class from `std::error_category`, override `name()` and `message(int)`, and expose **one** instance through a function returning a reference to a function-local static. 3. Provide `std::error_code make_error_code(build_errc)` in the same namespace as the enum, so it is found by argument-dependent lookup. 4. Specialize `std::is_error_code_enum<build_errc>` as `std::true_type`, which enables the implicit `error_code` constructor from the enum. With that, `std::error_code ec = build_errc::missing_source;` works, and the second snippet prints it as `build:1 source file missing`. If the tool later maps its codes to process exit statuses, the mapping lives in `main`. ## From error codes to the tool's exit status The process status and an `error_code` are different things: one is a small integer the host reads, the other a typed value with a category. A build tool joins them in exactly one place, `main`: - Inside the tool, functions return or throw `error_code`s and `system_error`s with full detail. - `main` maps categories to a handful of documented statuses, for example `build_category()` failures to one value, `generic_category()` I/O failures to another, everything else to `EXIT_FAILURE`. - The message from `ec.message()` or `e.what()` goes to standard error before `main` returns. Keeping the mapping in one function means the CI contract cannot drift as new error values are added. ## When to use which - Use `error_code` on hot or expected failure paths and at C API boundaries. - Use `system_error` (or a derived type) when the failure is exceptional and should unwind. - Never compare categories by name; compare by identity, and keep exactly one instance of each custom category.
- Why must a custom error_category have exactly one instance?Categories compare by address: `error_category::operator==` returns `this == &rhs`, and `error_code` equality compares categories that way. Two instances of the same category class would make otherwise identical codes compare unequal. The usual implementation returns a reference to a function-local static, which also gives thread-safe initialization.
- Why does error_code have an explicit operator bool rather than an is_error() member?`if (ec)` reads naturally: it is true when `value() != 0`, meaning an error was reported. Making the conversion `explicit` prevents accidental use of an `error_code` as an integer or in arithmetic. It also sets a convention every custom category should follow: value `0` means success, because a zero code tests as no error whatever its category.
- Comparing ec.value() with ENOENT is the portable check.
- Two error_codes with the same value are equal whatever their categories.
- Custom categories can be created per call and compared by name.
- std::error_code ec = std::errc::permission_denied; compiles.