Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::system_error — an exception carrying an error code

std::system_error combines an error code with diagnostic text. It lets low-level errors travel as exceptions while retaining structured information for identifying the cause programmatically.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <system_error>
std::system_error(ec)
std::system_error(ec, what_arg)
std::system_error(value, category)
std::system_error(value, category, what_arg)
const std::error_code& code() const noexcept;
const char* what() const noexcept override;

std::system_error, declared in <system_error>, derives from std::runtime_error. It represents an exception carrying an error code, typically from the operating system or a low-level API. Constructing the object does not itself throw it — throw does. The constructor can itself throw an exception, however, for example if allocating memory for the diagnostic text fails.

Constructors accept a std::error_code or an integer and an error category, optionally with a std::string or const char* description. code() returns the code by const reference; what() provides diagnostic text. Do not assume a particular format or language for that text; make decisions using the code rather than parsing the message.

The example deliberately throws an error without performing an operating-system operation. std::make_error_code(std::errc::permission_denied) creates a generic-category code. Comparing it with the saved code produces deterministic output without printing the implementation-dependent what().

Examples

#include <iostream>
#include <system_error>

int main() {
    const auto expected = std::make_error_code(std::errc::permission_denied);
    try {
        throw std::system_error(expected, "demo operation");
    } catch (const std::system_error& e) {
        std::cout << std::boolalpha
                  << "code preserved: " << (e.code() == expected) << '\n';
    }
}

Result

code preserved: true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources