命名空间
变体
操作

std::bad_exception

来自 cppreference.cn
< cpp‎ | 错误
 
 
 
 
 
定义于头文件 <exception>
class bad_exception;

std::bad_exception 是 C++ 运行时在以下情况下抛出的异常类型:

  • 如果 std::exception_ptr 存储了捕获到的异常的副本,并且如果 std::current_exception 捕获的异常对象的复制构造函数抛出异常,则捕获到的异常是 std::bad_exception 的实例。
(C++11 起)
  • 如果 动态异常规范 被违反,并且 std::unexpected 抛出或重新抛出仍然违反异常规范的异常,但异常规范允许 std::bad_exception,则抛出 std::bad_exception
(C++17 前)
cpp/error/exceptionstd-bad exception-inheritance.svg

继承图

std::bad_exception 的所有成员函数都是 constexpr

(C++26 起)

目录

[编辑] 成员函数

构造 bad_exception 对象
(公开成员函数)
复制对象
(公开成员函数)
[虚函数]
返回解释字符串
(虚公共成员函数)

继承自 std::exception

成员函数

[虚函数]
销毁异常对象
(std::exception 的虚公共成员函数) [编辑]
[虚函数]
返回解释字符串
(std::exception 的虚公共成员函数) [编辑]

[编辑] 注意

特性测试 标准 特性
__cpp_lib_constexpr_exceptions 202411L (C++26) 异常类型的 constexpr

[编辑] 示例

仅在 C++14 或更早的模式下编译(可能会发出警告)。

#include <exception>
#include <iostream>
#include <stdexcept>
 
void my_unexp()
{
    throw;
}
 
void test()
    throw(std::bad_exception) // Dynamic exception specifications
                              // are deprecated in C++11
{
    throw std::runtime_error("test");
}
 
int main()
{
    std::set_unexpected(my_unexp); // Deprecated in C++11, removed in C++17
 
    try
    {
        test();
    }
    catch (const std::bad_exception& e)
    {
        std::cerr << "Caught " << e.what() << '\n';
    }
}

可能的输出

Caught std::bad_exception