-2

What I have tried:

class MyException : public std::runtime_error {};

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

I am not sure how I can implement such a feature.

John Smith
  • 63
  • 1
  • 4
  • Spending time in the *thousands* of "C++ Custom Exception Objects" hits from Google will likely pay off more than coming here and being abused for not asking an actual question. The [recommended book list for C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?rq=1) has some outstanding sections on stuff like this as well. – WhozCraig Oct 31 '13 at 22:34

2 Answers2

0

You need to define a constructor function for MyException which accepts a string and then sends it to std::runtime_error's constructor. Something like this:

class MyException : public std::runtime_error {
public:
    MyException(std::string str) : std::runtime_error(str)
    {
    }
};
NapoleonBlownapart
  • 309
  • 1
  • 2
  • 8
0

There are two issues here: how to have your exception accept a string parameter, and how to create a string from runtime information.

class MyException : public std::runtime_error 
{
    MyExcetion(const std::string& message) // pass by const reference, to avoid unnecessary copying
    :  std::runtime_error(message)
    {}          
};

Then you have different ways to construct the string argument:

  1. std::to_string is most convenient, but is a C++11 function.

    throw MyException(std::string("Out of bounds, should be between 0 and ") 
                      + std::to_string(limit));
    
  2. Or use boost::lexical_cast (function name is a link).

    throw MyException(std::string("Out of bounds, should be between 0 and ")
                      + boost::lexical_cast<std::string>(limit));
    
  3. You could also create a C-string buffer and use a printf style command. std::snprintf would be preferred, but is also 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);
    
NicholasM
  • 4,557
  • 1
  • 20
  • 47