c++boostlexical-cast

When does boost::lexical_cast to std::string fail?


I'm writing unit tests and trying to have all my code covered.

I have in my code something like this:

template<typename ValueType>
std::string ConvertToStringUsingBoost(ValueType const& v)
{
    try 
    {
        return boost::lexical_cast<std::string, ValueType>(v);
    }
    catch(boost::bad_lexical_cast const& e)
    {
        LOG_ERR("Fail to cast %s to string", e.source_type().name);
        return std::string();
    }
}

I was reading these docs and couldn't find any information about when boost::lexical_cast to std::string can throw an exception.

Can you please help me with that?

If it's impossible I'll simply delete this try-catch. If it's possible, I'd prefer to cover this in unit testing.


Solution

  • It can fail for example if a user-defined conversion throws:

    enum class MyType {};
    
    std::ostream& operator<<( std::ostream&, MyType const& )
    {
        throw "error";
    }
    
    int main()
    {
        try 
        {
            boost::lexical_cast< std::string >( MyType{} );
        }
        catch(...)
        {
            std::cout << "lexical_cast exception";
        }
    }
    

    As you have no control about the type of exceptions thrown by user-defined conversions, catching boost::bad_lexical_cast won't even be enough. Your unit test has to catch all exceptions.

    Live Demo