Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::logic_error — program logic exception

std::logic_error, declared in <stdexcept>, represents errors in a program's internal logic, such as violated preconditions or class invariants. It stores a message available through what() and derives from std::exception.

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

Syntax

#include <stdexcept>

/* Constructor declarations from std::logic_error (C++23 synopsis excerpt):
namespace std {
    class logic_error : public exception {
    public:
        explicit logic_error(const std::string& what_arg);
        explicit logic_error(const char* what_arg);
        // Other members omitted.
    };
}
*/

void f() {
    throw std::logic_error("message");
}

std::logic_error is an exception class declared in <stdexcept> that publicly derives from std::exception. It represents theoretically preventable errors in program logic, such as calling an operation before required configuration. It does not mean a compilation error: this exception can be thrown while the program runs.

Its constructors accept a message as either const std::string& or const char* and are explicit. The what() member exposes the message text. Throw by value and catch by const std::logic_error&, as the example does.

std::invalid_argument, std::domain_error, std::length_error, and std::out_of_range are derived classes; choose a more specific type when it fits the error. std::runtime_error is a separate branch for errors associated with events outside the program's logic. Violating a precondition does not itself guarantee a std::logic_error: the example explicitly detects the problem and executes throw.

The example targets C++23 compilation mode. The supplied site presents an evolving working draft, not frozen C++23 wording; its displayed constexpr constructors are not treated here as C++23 functionality. Production runtime behavior has not been attested.

Examples

#include <iostream>
#include <stdexcept>

void start(bool configured) {
    if (!configured) {
        throw std::logic_error("configuration required");
    }
}

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

Result

configuration required

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