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