Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::runtime_error — runtime error exception

std::runtime_error, declared in <stdexcept>, reports errors detectable during program execution. It carries a message accessible through what() and publicly derives from std::exception.

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

Syntax

#include <stdexcept>

// C++23
explicit runtime_error(const std::string& what_arg);
explicit runtime_error(const char* what_arg);

throw std::runtime_error("Service unavailable");

std::runtime_error is an exception class from <stdexcept> that publicly derives from std::exception. It represents errors presumably detectable only during execution, such as an unavailable service. In contrast, std::logic_error describes errors in the program's internal logic that are theoretically preventable.

Its constructors accept a message what_arg as const std::string& or const char*. The what() function returns a pointer to null-terminated text. After construction, strcmp(what(), what_arg.c_str()) == 0 for the first overload and strcmp(what(), what_arg) == 0 for the second. If the supplied std::string contains an embedded null character ('\0'), what() need not preserve any characters after it. The what() function does not throw. The returned pointer remains valid until the exception object is destroyed or one of its non-const member functions is called; copy the text into std::string if it must live longer.

Use throw to raise the exception, and catch it through const std::runtime_error& to avoid copying. Merely constructing the object does not throw it as an exception. In the example, false deterministically simulates an unavailable service, and the catch block prints Service unavailable followed by a newline.

This entry targets C++23. The supplied working draft evolves and also shows constexpr declarations that must not be treated as C++23 guarantees. A repository compiler flag does not establish production runtime behavior; the example requires local verification.

Examples

#include <iostream>
#include <stdexcept>

void access_service(bool available) {
    if (!available) {
        throw std::runtime_error("Service unavailable");
    }
}

int main() {
    try {
        access_service(false);
    } catch (const std::runtime_error& error) {
        std::cout << error.what() << '\n';
    }
}

Result

Service unavailable

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