动态异常规定
列出函数可能直接或间接抛出的异常。
目录 |
[编辑] 语法
throw( )
|
(1) | (C++11 中弃用) | |||||||
throw(typeid, typeid, ...)
|
(2) | (C++11 中弃用)(C++17 前) | |||||||
|
1) 不抛出动态异常规定
|
(C++17 前) |
|
1) 与 noexcept(true) 相同
|
(C++17 起) |
此规定仅可出现在作为类型为函数类型、指向函数的指针类型、到函数的引用类型、指向成员函数的指针类型的函数、变量、非静态数据成员的声明器的,顶层 (C++17 前) lambda 声明器或函数声明器上。它可以出现在参数的声明器或返回类型的声明器上。
void f() throw(int); // OK :函数声明 void (*fp)() throw (int); // OK :指向函数的指针声明 void g(void pfa() throw(int)); // OK :指向函数指针参数声明 typedef int (*pf)() throw(int); // 错误: typedef 声明
[编辑] 解释
若函数声明带有列于其异常规定的类型 T ,则函数可能抛出该类型或从该类型导出的类型的异常。
不完整类型、指针或到异于 cv void* 的不完整类型引用,及右值引用类型在异常规定中不允许。若使用数组和函数类型,则它们被调整到对应的指针类型。允许参数包。 (C++11 起)
若函数抛出不列于其异常规定的类型的异常,则调用函数 std::unexpected 。函数默认调用 std::terminate ,但它可以为可能调用 std::terminate 或抛出异常的用户提供函数(通过 std::set_unexpected )替换。若从 std::unexpected 抛出的异常为异常规定所接受,则栈回溯照常持续。若它不被接受,但异常规定允许 std::bad_exception ,则抛出 std::bad_exception 。否则,调用 std::terminate 。
潜在异常每个函数 2) 否则,若
f 、 fp 或 mfp 使用动态异常规定(弃用),则集合由列于该规定的所有类型组成3) 否则,集合是所有类型的集合
注意:对于隐式声明的特殊成员函数(构造函数、赋值运算符及析构函数),及对于继承的构造函数,潜在异常的集合是它们会调用的所有函数的潜在异常集合的并集:非变体非静态数据成员、直接基类及适当场合的虚基类的构造函数/赋值运算符/析构函数(还包括默认参数表达式) 每个表达式 1) 若
e 是一个函数调用表达式,且
void f() throw(int); // f() 的集合是“ int ” void g(); // g() 的集合是所有类型的集合 struct A { A(); }; // “ new A ”的集合是所有类型的集合 struct B { B() noexcept; }; // “ B() ”的集合为空 struct D() { D() throw (double); }; // “ new D ”的集合是所有类型的集合 所有隐式声明的成员函数(及继承的构造函数)拥有异常规定,选择如下:
struct A { A(int = (A(5), 0)) noexcept; A(const A&) throw(); A(A&&) throw(); ~A() throw(X); }; struct B { B() throw(); B(const B&) = default; // 异常规定是“ noexcept(true) ” B(B&&, int = (throw Y(), 0)) noexcept; ~B() throw(Y); }; int n = 7; struct D : public A, public B { int * p = new (std::nothrow) int[n]; // D 拥有下列隐式声明的成员: // D::D() throw(X, std::bad_array_new_length); // D::D(const D&) noexcept(true); // D::D(D&&) throw(Y); // D::~D() throw(X, Y); }; |
(C++17 起) |
[编辑] 示例
#include <iostream> #include <exception> #include <cstdlib> class X {}; class Y {}; class Z : public X {}; class W {}; void f() throw(X, Y) { int n = 0; if (n) throw X(); // OK if (n) throw Z(); // 亦 OK throw W(); // 将调用 std::unexpected() } int main() { std::set_unexpected([]{ std::cout << "That was unexpected" << std::endl; // 需要冲入 std::abort(); }); f(); }
输出:
That was unexpected

