How to throw std::exceptions with variable messages?

前端 未结 8 2097
梦如初夏
梦如初夏 2020-12-04 08:00

This is an example of what I often do when I want to add some information to an exception:

std::stringstream errMsg;
errMsg << \"Could not load config          


        
8条回答
  •  没有蜡笔的小新
    2020-12-04 08:38

    A really nicer way would be creating a class (or classes) for the exceptions.

    Something like:

    class ConfigurationError : public std::exception {
    public:
        ConfigurationError();
    };
    
    class ConfigurationLoadError : public ConfigurationError {
    public:
        ConfigurationLoadError(std::string & filename);
    };
    

    The reason is that exceptions are much more preferable than just transferring a string. Providing different classes for the errors, you give developers a chance to handle a particular error in a corresponded way (not just display an error message). People catching your exception can be as specific as they need if you use a hierarchy.

    a) One may need to know the specific reason

    } catch (const ConfigurationLoadError & ex) {
    // ...
    } catch (const ConfigurationError & ex) {
    

    a) another does not want to know details

    } catch (const std::exception & ex) {
    

    You can find some inspiration on this topic in https://books.google.ru/books?id=6tjfmnKhT24C Chapter 9

    Also, you can provide a custom message too, but be careful - it is not safe to compose a message with either std::string or std::stringstream or any other way which can cause an exception.

    Generally, there is no difference whether you allocate memory (work with strings in C++ manner) in the constructor of the exception or just before throwing - std::bad_alloc exception can be thrown before the one which you really want.

    So, a buffer allocated on the stack (like in Maxim's answer) is a safer way.

    It is explained very well at http://www.boost.org/community/error_handling.html

    So, the nicer way would be a specific type of the exception and be avoiding composing the formatted string (at least when throwing).

提交回复
热议问题