Adding exception info to boost::exception’s

Maybe this is one of those things buried in the documentation that I missed, it’s quite possible. I generally don’t read documentation but instead scan it for code samples.

The other day I realized that my boost::exception derived exceptions were not storing any error_info data that I put into them. For example:

class MyException : public boost::exception
{
public:
	MyException() = default;

    MyException(const std::string& custommsg)
        : _message(custommsg), _line(0)
    {}
    
private:
	std::string _message;
};

template<class E>
void ThrowException(const E & ex, const char * function, int line)
{
	throw (ex << boost::throw_function(function) 
    	<< boost::errinfo_at_line(line));
}

#define THROW_EXCEPTION(x)      ThrowException((x), BOOST_CURRENT_FUNCTION, __LINE__);

I would pass the exceptions around by const reference, yet when I went to retrieve the information, it was all null!

I finally figured out that the problem was the lack of a proper copy constructor. I am still not entirely sure why I need a copy-constructor since the exceptions are supposedly being passed around by reference, but that did the trick.

class MyException : public boost::exception
{
public:
	MyException() = default;

    MyException(const std::string& custommsg)
        : _message(custommsg), _line(0)
    {}
    
	MyException(const MyException& other)
        : boost::exception(other)
	{
		_message = other.message();
	}
    
    
private:
	std::string _message;
};