C++ 抛出错误消息C++;

C++ 抛出错误消息C++;,c++,exception,C++,Exception,我所尝试的: class MyException : public std::runtime_error {}; throw MyException("Sorry out of bounds, should be between 0 and "+limit); 我不确定如何实现这样一个功能。您需要为MyException定义一个构造函数,它接受一个字符串,然后将它发送给std::runtime\u error的构造函数。大概是这样的: class MyException : public s

我所尝试的:

class MyException : public std::runtime_error {};

throw MyException("Sorry out of bounds, should be between 0 and "+limit);

我不确定如何实现这样一个功能。

您需要为MyException定义一个构造函数,它接受一个字符串,然后将它发送给std::runtime\u error的构造函数。大概是这样的:

class MyException : public std::runtime_error {
public:
    MyException(std::string str) : std::runtime_error(str)
    {
    }
};

这里有两个问题:如何让异常接受字符串参数,以及如何从运行时信息创建字符串

class MyException : public std::runtime_error 
{
    MyExcetion(const std::string& message) // pass by const reference, to avoid unnecessary copying
    :  std::runtime_error(message)
    {}          
};
然后有不同的方法来构造字符串参数:

  • 是最方便的,但是是一个C++11函数

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


  • 花时间在谷歌数千个“C++自定义异常对象”的点击上,可能会比来到这里,因为没有问一个实际问题而被滥用得到更多回报。《华尔街日报》也有一些关于这类东西的优秀章节。约翰·史密斯,谢谢。我为将来的读者编辑和修改了。
    throw MyException(std::string("Out of bounds, should be between 0 and ")
                      + boost::lexical_cast<std::string>(limit));
    
    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);