std::domain_error

来自cppreference.com
< cpp‎ | error
在标头 <stdexcept> 定义
class domain_error;

定义作为异常抛出的对象类型。实现可用它报告定义域错误,即输入在操作有定义的定义域外的情形。

标准库组件不会抛出此异常(数学函数报告按以 math_errhandling 指定的方式定义域错误)。然而第三方库会使用它。例如,boost.math 在启用 boost::math::policies::throw_on_error(默认设置)时会抛出 std::domain_error

cpp/error/exceptioncpp/error/logic errorstd-domain error-inheritance.svg

继承图

成员函数

(构造函数)
构造拥有给定消息的新 domain_error 对象
(公开成员函数)
operator=
替换 domain_error 对象
(公开成员函数)

std::domain_error::domain_error

domain_error( const std::string& what_arg );
(1)
domain_error( const char* what_arg );
(2)
(3)
domain_error( const domain_error& other );
(C++11 前)
domain_error( const domain_error& other ) noexcept;
(C++11 起)
1) 构造以 what_arg 作为解释字符串的异常对象。构造后 std::strcmp(what(), what_arg.c_str()) == 0
2) 构造以 what_arg 作为解释字符串的异常对象。构造后 std::strcmp(what(), what_arg) == 0
3) 复制构造函数。如果 *thisother 的动态类型都是 std::domain_error,那么 std::strcmp(what(), other.what()) == 0复制构造函数不能抛出异常。 (C++11 前)

参数

what_arg - 解释字符串
other - 要复制的另一异常对象

异常

1-2) 可能抛出 std::bad_alloc

注解

因为不容许复制 std::domain_error 抛出异常,通常将此消息在内部存储为分离分配的引用计数字符串。这也是构造函数不接收 std::string&& 参数的理由:无论如何它必须复制内容。

在解决 LWG 问题 254 之前,非复制的构造函数只接受 std::string。这导致因需要构造 std::string 对象而不得不进行动态内存分配。

在解决 LWG 问题 471 之后,派生的标准异常类必须有一个公开可访问的复制构造函数。它可以隐式定义,只要分别在原对象和复制对象上通过 what() 获得的两个解释字符串相同。

std::domain_error::operator=

domain_error& operator=( const domain_error& other );
(C++11 前)
domain_error& operator=( const domain_error& other ) noexcept;
(C++11 起)

other 的内容用于赋值。 如果 *thisother 的动态类型都是 std::domain_error,那么在赋值后 std::strcmp(what(), other.what()) == 0复制赋值运算符不能抛出异常。 (C++11 前)

Parameters

other - 要赋值来的另一异常对象

Return value

*this

Notes

在解决 LWG 问题 471 之后,派生的标准异常类必须有一个公开可访问的复制赋值运算符。它可以隐式定义,只要分别在原对象和复制对象上通过 what() 获得的两个解释字符串相同。

继承自 std::logic_error

继承自 std::exception

成员函数

析构该异常对象
(std::exception 的虚公开成员函数)
[虚]
返回解释性字符串
(std::exception 的虚公开成员函数)

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 254 C++98 缺失了接受 const char* 的构造函数 已补充
LWG 471 C++98 std::domain_error 的复制的解释字符串由实现定义 它们与原 std::domain_error 对象的解释字符串相同