std::bad_exception

来自cppreference.com
< cpp‎ | error
 
 
 
 
 
在标头 <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) // C++11 摒弃了动态异常说明
{
    throw std::runtime_error("test");
}
 
int main()
{
    std::set_unexpected(my_unexp); // C++11 中摒弃,C++17 中移除
 
    try
    {
        test();
    }
    catch (const std::bad_exception& e)
    {
        std::cerr << "捕获到 " << e.what() << '\n';
    }
}

可能的输出:

捕获到 std::bad_exception