Namespaces
Variants

std:: format_error

From cppreference.net
定义于头文件 <format>
class format_error : public runtime_error
(C++20 起)

定义在格式化库中用于报告错误的异常对象类型。

std::format_error 的所有成员函数均为 constexpr :可以在常量表达式求值过程中创建和使用 std::format_error 对象。

std::format_error 对象通常不能是 constexpr ,因为任何动态分配的存储必须在同一常量表达式求值过程中释放。

(since C++26)
cpp/error/exception cpp/error/runtime error std-format error-inheritance.svg

继承关系图

目录

成员函数

(constructor)
使用给定消息构造新的 format_error 对象
(公开成员函数)
operator=
替换 format_error 对象
(公开成员函数)

std::format_error:: format_error

format_error ( const std:: string & what_arg ) ;
(1) (constexpr since C++26)
format_error ( const char * what_arg ) ;
(2) (constexpr since C++26)
format_error ( const format_error & other ) noexcept ;
(3) (constexpr since C++26)
1) 使用 what_arg 作为解释字符串构造异常对象。构造后满足 std:: strcmp ( what ( ) , what_arg. c_str ( ) ) == 0
2) 使用 what_arg 作为解释字符串构造异常对象。构造后满足 std:: strcmp ( what ( ) , what_arg ) == 0
3) 拷贝构造函数。如果 * this other 都具有动态类型 std::format_error ,则满足 std:: strcmp ( what ( ) , other. what ( ) ) == 0 。拷贝构造函数不允许抛出任何异常。

参数

what_arg - 解释性字符串
other - 要拷贝的另一个异常对象

异常

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

注解

由于不允许在拷贝 std::format_error 时抛出异常,因此异常消息通常作为单独分配、引用计数的字符串在内部存储。这也是为什么没有接受 std::string&& 参数的构造函数:无论如何都需要复制内容。

派生的标准异常类必须具有公开可访问的拷贝构造函数。只要原始对象和拷贝对象通过 what() 获得的解释字符串相同,该构造函数可以隐式定义。

std::format_error:: operator=

format_error & operator = ( const format_error & other ) noexcept ;
(constexpr since C++26)

使用 other 的内容进行赋值。如果 * this other 都具有动态类型 std::format_error ,则赋值后满足 std:: strcmp ( what ( ) , other. what ( ) ) == 0 。复制赋值运算符不会抛出任何异常。

参数

other - 用于赋值的另一个异常对象

返回值

* this

注解

派生的标准异常类必须具有公开可访问的复制赋值运算符。只要原始对象和复制对象通过 what() 获得的说明字符串相同,该运算符就可以隐式定义。

继承自 std:: exception

成员函数

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

注释

功能测试 标准 功能特性
__cpp_lib_constexpr_exceptions 202502L (C++26) constexpr 异常类型

示例

#include <format>
#include <print>
#include <string_view>
#include <utility>
int main()
{
    try
    {
        auto x13{37};
        auto args{std::make_format_args(x13)};
        std::ignore = std::vformat("{:()}", args); // 抛出异常
    }
    catch(const std::format_error& ex)
    {
        std::println("{}", ex.what());
    }
}

可能的输出:

format error: failed to parse format-spec

参见