带有printf样式字符串的c++异常类

C++ exception class with printf style string?

本文关键字:c++ 异常 字符串 printf 样式 带有      更新时间:2023-10-16

在c++ 11中,是否有一种简单的(或者更好的,内置的)方法可以在异常中执行类似print样式的字符串?

throw std::runtime_error( "Failed to open '%s' [%d]: %s", 
         filename, errno, strerror(errno) );

我知道我可以将snprintf转换为' char[]',然后将结果传递给异常构造函数,或w/o首先转换为std::string。

只是想知道c++ 11是否有更好/更简单的东西。

从c++ 11开始,您可以从std::string中构造异常:

std::runtime_error("Failed to open " + std::string(filename) + std::to_string(errno));

这有一个轻微的缺点,std::string的构造函数可能会throw,从而终止您的程序。然而,这应该只在处理某种"内存不足"异常时才会起作用。

如果您只是在谈论创建格式化字符串,您可以使用std::to_string连接

throw std::runtime_error(std::string("Failed to open ") + filename +  "[" + std::to_string(errno) + "]: " + strerror(errno));