带有printf样式字符串的c++异常类
C++ exception class with printf style string?
在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));
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常