抛出并显示错误消息C++

Throw with Error Message C++

本文关键字:消息 C++ 错误 显示      更新时间:2023-10-16

>我尝试过的:

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)
    {}          
};

然后,您有不同的方法来构造字符串参数:

  1. std::to_string是最方便的,但是一个C++11功能。

    throw MyException(std::string("Out of bounds, should be between 0 and ") 
                      + std::to_string(limit));
    
  2. 或者使用 boost::lexical_cast(函数名称是一个链接)。

    throw MyException(std::string("Out of bounds, should be between 0 and ")
                      + boost::lexical_cast<std::string>(limit));
    
  3. 您还可以创建 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)
    {
    }
};