抛出并显示错误消息C++
Throw with Error Message C++
>我尝试过的:
class MyException : public std::runtime_error {};
throw MyException("Sorry out of bounds, should be between 0 and "+limit);
我不确定如何实现这样的功能。
这里有两个问题:如何让异常接受字符串参数,以及如何从运行时信息创建字符串。
class MyException : public std::runtime_error
{
MyExcetion(const std::string& message) // pass by const reference, to avoid unnecessary copying
: std::runtime_error(message)
{}
};
然后,您有不同的方法来构造字符串参数:
std::to_string
是最方便的,但是一个C++11功能。throw MyException(std::string("Out of bounds, should be between 0 and ") + std::to_string(limit));
或者使用
boost::lexical_cast
(函数名称是一个链接)。throw MyException(std::string("Out of bounds, should be between 0 and ") + boost::lexical_cast<std::string>(limit));
您还可以创建 C 字符串缓冲区并使用 printf 样式命令。
std::snprintf
是首选,但也C++11。char buffer[24]; int retval = std::sprintf(buffer, "%d", limit); // not preferred // could check that retval is positive throw MyException(std::string("Out of bounds, should be between 0 and ") + buffer);
你需要为 MyException 定义一个构造函数,它接受一个字符串,然后将其发送到 std::runtime_error 的构造函数。 像这样:
class MyException : public std::runtime_error {
public:
MyException(std::string str) : std::runtime_error(str)
{
}
};
相关文章:
- boost::进程间消息队列引发错误
- 在线编译器中的分段C++没有打印消息
- C++错误消息*成员参考.**初学者*
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何通过参数抛出错误消息
- 从服务器传输到客户端的消息不会出现
- ROS2 动态消息模板
- C++秘密消息学校作业
- glad 导致 glfwSwapBuffers 返回错误消息
- C++入门 5 版:类消息和文件夹
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 由于无效的 ValidateRgn() 子窗口不会收到WM_PAINT消息
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 如何将 Firebase 与基于 Linux 的客户端应用配合使用,以便与服务器进行双向消息通信
- 重新定义预定义的 errno 错误消息 (E2BIG)
- Libmosquitto publish 不会将所有消息传递到 Azure IoT Hub
- 在 capnp FlatArrayMessageReader 的对齐内存缓冲区中接收 zmq 消息