C++ 标准库 - <exception>
简介
它是一个标准的异常类。 标准库的组件抛出的所有对象都派生自这个类。 因此,所有标准异常都可以通过引用捕获此类型来捕获。
声明
以下是 std::exception 的声明。
class exception;
示例
在下面的 std::exception 示例中。
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
std::atomic_flag lock = ATOMIC_FLAG_INIT;
void f(int n) {
for (int cnt = 0; cnt < 100; ++cnt) {
while (lock.test_and_set(std::memory_order_acquire))
;
std::cout << "Output from thread " << n << '\n';
lock.clear(std::memory_order_release);
}
}
int main() {
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n) {
v.emplace_back(f, n);
}
for (auto& t : v) {
t.join();
}
}
派生类型
| 序号 | 派生类型 | 定义 |
|---|---|---|
| 1 | bad_alloc | 分配内存失败时抛出此异常 |
| 2 | bad_cast | 动态转换失败时抛出此异常 |
| 3 | bad_exception | 这是意外处理程序引发的异常 |
| 4 | bad_function_call | 错误调用引发此异常 |
| 5 | bad_typeid | 在空指针的 typeid 上抛出此异常 |
| 6 | bad_weak_ptr | 这是一个不好的弱指针 |
| 7 | ios_base::failure | 它是流异常的基类 |
| 8 | logic_error | 这是一个逻辑错误异常 |
| 9 | runtime_error | 这是一个运行时错误异常 |
派生类型(通过 logic_error)
| 序号 | 派生类型 | 定义 |
|---|---|---|
| 1 | domain_error | 这是域错误异常 |
| 2 | future_error | 这是一个未来的错误异常 |
| 3 | invalid_argument | 这是一个无效的参数异常 |
| 4 | length_error | 这是一个长度错误异常 |
| 5 | out_of_range | 这是一个超出范围的异常 |
派生类型(通过 runtime_error)
| 序号 | 派生类型 | 定义 |
|---|---|---|
| 1 | overflow_error | 这是一个溢出错误异常 |
| 2 | range_error | 这是一个范围错误异常 |
| 3 | system_error | 这是一个系统错误异常 |
| 4 | underflow_error | 这是一个下溢错误异常 |
派生类型(通过 bad_alloc)
| 序号 | 派生类型 | 定义 |
|---|---|---|
| 1 | bad_array_new_length | 这是错误数组长度的例外 |
派生类型(通过 system_error,自 C++11 起)
| 序号 | 派生类型 | 定义 |
|---|---|---|
| 1 | ios_base::failure | 它是流异常的基类 |
成员函数
| 序号 | 派生类型 | 定义 |
|---|---|---|
| 1 | (constructor) | 这是构造函数异常 |
| 2 | operator= | 这是一个复制异常 |
| 3 | what | 用于获取字符串识别异常 |
| 4 | (destructor) | 这是一个销毁异常 |

