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

I can't think of any reason for lexical cast to string to throw bad_lexical_cast, except with user-defined types. If the ValueType stream insertion operator can set an error flag on the stream then that's going to result in a bad_lexical_cast. Otherwise, not.

Personally I'd keep the catch in, even if you're just converting built-ins like ints; it doesn't hurt, and may catch bugs if you change the lexical_cast in some manner, or if there's some edge case that neither you nor I has considered; if you're not handling the resulting exception, you'll get an abort at runtime!

If you're concerned about the overhead of an exception, you can use try_lexical_cast instead and check that it returns true rather than catching. However, if the ValueType stream insertion operator can throw then you'd still need to be able to catch that exception anyway.


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