c++exception

How to throw std::exceptions with variable messages?


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 file '" << configfile << "'";
throw std::exception(errMsg.str().c_str());

Is there a nicer way to do it?


Solution

  • Here is my solution:

    #include <stdexcept>
    #include <sstream>
    
    class Formatter
    {
    public:
        Formatter() {}
        ~Formatter() {}
    
        template <typename Type>
        Formatter & operator << (const Type & value)
        {
            stream_ << value;
            return *this;
        }
    
        std::string str() const         { return stream_.str(); }
        operator std::string () const   { return stream_.str(); }
    
        enum ConvertToString 
        {
            to_str
        };
        std::string operator >> (ConvertToString) { return stream_.str(); }
    
    private:
        std::stringstream stream_;
    
        Formatter(const Formatter &);
        Formatter & operator = (Formatter &);
    };
    

    Example:

    throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData);   // implicitly cast to std::string
    throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str);    // explicitly cast to std::string