CKTIS / C++
std::exception: polymorfe basis voor bibliotheekexcepties
std::exception is de basis van standaard runtime-excepties; de virtuele what() retourneert zonder te werpen een implementatiebepaalde nulbeëindigde beschrijving.
Versie: 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 uit <exception> heeft standaard- en kopieconstructie, kopietoewijzing, een virtuele destructor en virtual const char* what() const noexcept. De virtuele destructor en what() maken afhandeling van afgeleide excepties via const std::exception& mogelijk zonder verlies van het dynamische type.
Afgeleide standaardklassen melden tijdens uitvoering gevonden fouten. Voor kopieën van twee objecten met hetzelfde dynamische type eist de standaard tekstueel gelijke what()-resultaten. De basistekst van std::exception::what() is implementatiebepaald en mag geen programmalogica sturen.
Vang niet op waarde, want dat snijdt het object af; vang via const&. Een eigen what()-override moet noexcept blijven en naar nulbeëindigde tekst wijzen die tijdens gebruik geldig is; bewaar die pointer niet nadat het exceptieobject is vernietigd.
Voorbeelden
#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';
}
}
Resultaat
parse error
std::exception → parse error