CKTIS / C++
std::format_error — formatting error exception
std::format_error, declared in <format>, reports errors from the formatting library. Learn the distinction between a runtime exception and compile-time rejection of an invalid format string, and how to catch this exception safely.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <format>
// C++23 constructor signatures:
// std::format_error publicly derives from std::runtime_error.
explicit format_error(const std::string& what_arg);
explicit format_error(const char* what_arg);
// Catch by const reference:
catch (const std::format_error& e) { /* handle formatting error */ }std::format_error is an exception class declared in <format> that publicly derives from std::runtime_error. It reports errors from the formatting library. Catch it by const std::format_error& to avoid copying the object and retain access to its diagnostic message through what().
Its two explicit constructors accept const std::string& or const char*. For an exception you construct yourself, what() returns text matching the supplied null-terminated string. Do not, however, assume a particular diagnostic wording for exceptions generated by the library; the example prints its own fixed message.
In C++23, an invalid literal passed to std::format, such as std::format("{:d}", "hello"), causes a compilation error rather than a catchable exception. Use std::vformat with std::make_format_args for a pattern available at runtime. In the example, {:d} requires an integer, but the argument is a string, so std::format_error is thrown. The argument value stays alive throughout the call.
Not every formatting exception is a std::format_error: exceptions from formatters and iterators propagate, while allocation failures are reported separately. The cited working draft evolves and also shows changes beyond C++23; the syntax given here does not mark the constructors constexpr. A repository C++23 compiler flag does not attest library support in the production environment.
Examples
#include <format>
#include <iostream>
#include <string>
int main() {
std::string pattern = "{:d}";
std::string value = "hello";
try {
std::cout << std::vformat(pattern, std::make_format_args(value)) << '\n';
} catch (const std::format_error&) {
std::cout << "format_error caught\n";
return 0;
}
return 1;
}
Result
format_error caught
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.