C++ Exceptions with message

How about
throw std::runtime_error("My very own message");


In the constructor I have

Printer::Printer(boost::asio::io_service& io, unsigned int interval) {
    if (interval < 1) {
        throw std::runtime_error("Interval can't be less than one second");
    }
}

And when creating the object

try {
    Printer p{io, 0};
} catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}

the program will exit with the message thrown.


You can take advantage of std:string

class LoadException: public std::exception {
private:
    std::string message_;
public:
    explicit LoadException(const std::string& message);
    const char* what() const noexcept override {
        return message_.c_str();
    }
};


LoadException::LoadException(const std::string& message) : message_(message) {
    
}

Then the C++ scoping will take care of cleaning things up for you