How to throw std::exceptions with variable messages?

前端 未结 8 2085
梦如初夏
梦如初夏 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:51

    The standard exceptions can be constructed from a std::string:

    #include <stdexcept>
    
    char const * configfile = "hardcode.cfg";
    std::string const anotherfile = get_file();
    
    throw std::runtime_error(std::string("Failed: ") + configfile);
    throw std::runtime_error("Error: " + anotherfile);
    

    Note that the base class std::exception can not be constructed thus; you have to use one of the concrete, derived classes.

    0 讨论(0)
  • 2020-12-04 08:54

    The following class might come quite handy:

    struct Error : std::exception
    {
        char text[1000];
    
        Error(char const* fmt, ...) __attribute__((format(printf,2,3))) {
            va_list ap;
            va_start(ap, fmt);
            vsnprintf(text, sizeof text, fmt, ap);
            va_end(ap);
        }
    
        char const* what() const throw() { return text; }
    };
    

    Usage example:

    throw Error("Could not load config file '%s'", configfile.c_str());
    
    0 讨论(0)
提交回复
热议问题