Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::overflow_error — reporting arithmetic overflow

std::overflow_error, declared in <stdexcept>, reports arithmetic overflow. It does not detect overflow automatically: code must check bounds before a risky operation and explicitly throw the exception.

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

Syntax

#include <stdexcept>

// Constructor declarations in <stdexcept> (abridged):
// namespace std {
// class overflow_error : public runtime_error {
// public:
//     explicit overflow_error(const std::string& what_arg);
//     explicit overflow_error(const char* what_arg);
// };
// }

throw std::overflow_error("integer overflow");

std::overflow_error is an exception type declared in <stdexcept> for reporting arithmetic overflow. It publicly derives from std::runtime_error and indirectly from std::exception, so it can also be caught through a reference to either base class.

Its explicit constructors accept a message as const std::string& or const char*. The inherited what() method exposes the message as a null-terminated string that compares equal to the supplied text. Catching by const std::overflow_error& lets you read that message without copying the exception.

Using this type does not enable arithmetic checking. Overflow in built-in signed integer arithmetic has undefined behavior; try/catch does not convert it into an exception. Unsigned arithmetic operates modulo 2^N and likewise does not automatically throw std::overflow_error. Check bounds before the operation, rather than checking only its result.

The example checks whether incrementing an int would exceed its maximum. If so, it explicitly throws before evaluating value + 1, and the handler prints integer overflow. This entry targets C++23; the supplied living standard draft may show later additions, so the syntax does not mark the constructors constexpr.

Examples

#include <iostream>
#include <limits>
#include <stdexcept>

int checked_increment(int value) {
    if (value == std::numeric_limits<int>::max()) {
        throw std::overflow_error("integer overflow");
    }
    return value + 1;
}

int main() {
    try {
        const int result = checked_increment(std::numeric_limits<int>::max());
        std::cout << result << '\n';
    } catch (const std::overflow_error& error) {
        std::cout << error.what() << '\n';
    }
}

Result

integer overflow

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