Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::out_of_range — argument outside its expected range

std::out_of_range, declared in <stdexcept>, reports an argument value outside its expected range. It carries a message available through what() and derives from std::logic_error.

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

Syntax

#include <stdexcept>
throw std::out_of_range("message");
// Handler:
catch (const std::out_of_range& e) { /* use e.what() */ }

std::out_of_range is an exception class declared in <stdexcept> for reporting an argument value outside its expected range. It publicly derives from std::logic_error and indirectly from std::exception.

Its constructors accept a message as const std::string& or const char*. The what() member exposes text matching the supplied message. Catch the exception by const std::out_of_range&. Do not confuse it with std::range_error, which describes range errors in internal computations and derives from std::runtime_error.

In the example, checked_score explicitly checks the interval [0, 100] and rejects 101. The existence of this exception class does not add range checking to operations. The example targets C++23; the current working draft also includes later changes, so the constexpr constructors shown there are not a C++23 guarantee.

Examples

#include <iostream>
#include <stdexcept>

int checked_score(int score) {
    if (score < 0 || score > 100) {
        throw std::out_of_range("score must be in [0, 100]");
    }
    return score;
}

int main() {
    try {
        std::cout << checked_score(101) << '\n';
    } catch (const std::out_of_range& e) {
        std::cout << e.what() << '\n';
    }
}

Result

score must be in [0, 100]

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