Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::exception: polymorphic library-exception base

std::exception is the base of standard run-time exceptions; its virtual what() returns an implementation-defined null-terminated description without throwing.

Version: C++23

Syntax

class exception {
public:
    exception() noexcept;
    exception(const exception&) noexcept;
    exception& operator=(const exception&) noexcept;
    virtual ~exception();
    virtual const char* what() const noexcept;
};

std::exception from <exception> has default and copy construction, copy assignment, a virtual destructor, and virtual const char* what() const noexcept. The virtual destructor and what() allow derived exceptions to be handled through const std::exception& without losing their dynamic type.

Standard derived classes report errors detected during execution. For copies of two objects with the same dynamic type, the standard requires textually equal what() results. The base std::exception::what() text itself is implementation-defined, so program logic must not match it.

Do not catch by value because that slices the object; catch by const&. A custom what() override must remain noexcept and return a pointer to null-terminated text that stays valid while used; do not retain that pointer after the exception object is destroyed.

Examples

#include <exception>
#include <iostream>

class parse_error final : public std::exception {
public:
    const char* what() const noexcept override {
        return "parse error";
    }
};

int main() {
    try {
        throw parse_error{};
    } catch (const std::exception& error) {
        std::cout << error.what() << '\n';
    }
}

Result

parse error

std::exception → parse error

Sources