[英]C++ exception class with printf style string?
In C++11, is there an easy (or even better, built-in) way to do something like this to do printf-style strings in an exception? 在C ++ 11中,是否有一种简单的(甚至更好的内置)方式来执行此类操作以在异常中执行printf样式的字符串?
throw std::runtime_error( "Failed to open '%s' [%d]: %s",
filename, errno, strerror(errno) );
I know I could snprintf
to a `char []' then pass the result into an exception constructor with or w/o converting to std::string first. 我知道我可以将snprintf
传递给'char []',然后将结果传递给异常构造函数,或者先不转换为std :: string。
Just wondering if C++11 has anything better/simpler to offer. 只是想知道C ++ 11是否可以提供更好/更简单的功能。
Since C++11, you can construct exceptions from an std::string
: 从C ++ 11开始,您可以从std::string
构造异常:
std::runtime_error("Failed to open " + std::string(filename) + std::to_string(errno));
This has the slight drawback that the constructor of std::string
might throw
and thus terminate your program. 这有一个小缺点,即std::string
的构造函数可能会throw
并因此终止程序。 However, this should only come into play while handling some kind of "out of memory" exception. 但是,这仅在处理某种“内存不足”异常时才起作用。
如果您只是在谈论创建格式化字符串,则可以将串联与std::to_string
throw std::runtime_error(std::string("Failed to open ") + filename + "[" + std::to_string(errno) + "]: " + strerror(errno));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.