I'm currently working on my own exception class that inherits from std::exception
, and I'm not sure if I should make my own what()
or just call
std::exception("message")
in my class constructor.
This is my current code:
FilterException::FilterException(const char* message, int num) noexcept :
error_message(message), error_number(num) {}
const char* FilterException::what() const noexcept
{
return error_message.c_str();
}
FilterException::~FilterException() noexcept
{
}
int FilterException::getErrorNumber() const noexcept
{
return error_number;
}
So, my question, should I just leave it like this, or make a change in constructor and get rid of what()
?
First of all, the std::exception("message")
constructor is an implementation detail for VC++. It is not present in most other implementations.
Storing the what-message in a std::string
seems handy at first, but it adds a corner case for low memory situations: Copying the string might result in a bad_alloc
exception. And having a new exception happen while trying to handle the first one is not that good.
One option to deriving directly from std::exception
is to instead derive from one of the predefined exceptions in <stdexcept>
, for example std::runtime_error
. These exceptions do have constructors taking string parameters and have already somehow solved the double-exception problem. Probably by not storing a std::string
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With