Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::length_error — exceeding an allowable length

std::length_error, declared in <stdexcept>, reports an attempt to produce an object whose length exceeds its allowable limit. Learn its inheritance, message constructors, and handling through a const reference.

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

Syntax

#include <stdexcept>

// C++23 message constructor declarations inside class std::length_error:
// explicit length_error(const std::string& what_arg);
// explicit length_error(const char* what_arg);

throw std::length_error("length limit exceeded");
// Handle with: catch (const std::length_error& e)

std::length_error, declared in <stdexcept>, is an exception type reporting an attempt to produce an object whose length exceeds its maximum allowable size. It publicly derives from std::logic_error and indirectly from std::exception. Do not confuse it with std::out_of_range, which reports an argument outside its expected range.

Its constructors accept a message as const std::string& or const char*. The what() member exposes that message. Catch the exception through const std::length_error&; if you also handle base classes, place the more specific handler first.

The example deliberately checks a custom limit and executes throw std::length_error instead of forcing a huge allocation. With 9 > 8, it prints the supplied message. This demonstrates explicit exception throwing, not automatic library size checking.

This entry targets C++23. The supplied source is a live standard draft and also displays constexpr declarations, which must not be treated as a C++23 guarantee. The example does not require such constructors.

Examples

#include <cstddef>
#include <iostream>
#include <stdexcept>

void check_length(std::size_t requested) {
    constexpr std::size_t limit = 8;
    if (requested > limit) {
        throw std::length_error("length limit exceeded");
    }
}

int main() {
    try {
        check_length(9);
    } catch (const std::length_error& e) {
        std::cout << e.what() << '\n';
    }
}

Result

length limit exceeded

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