Exception class - what() function

喜欢而已 提交于 2021-02-08 19:42:36

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/48127473/exception-class-what-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!