Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception class - what() function

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() ?

like image 704
smiljanic997 Avatar asked Mar 08 '23 05:03

smiljanic997


1 Answers

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.

like image 143
Bo Persson Avatar answered Mar 12 '23 03:03

Bo Persson