抛出错误消息C ++

时间:2013-10-31 22:25:31

标签: c++ exception

我尝试过:

class MyException : public std::runtime_error {};

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

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

2 个答案:

答案 0 :(得分:0)

您需要为Exception定义一个构造函数,该函数接受一个字符串,然后将其发送到std :: runtime_error构造函数。像这样:

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

答案 1 :(得分:0)

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

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字符串缓冲区并使用a printf style commandstd::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);