When catching a boost::bad_lexical_cast, can I access the string/token which was to be cast?

400 views Asked by At

I'm running code which might throw a boost:bad_lexical_cast when casting a sequence of tokens - but I can't go into the code and "put the tokens aside" so I can figure out what cast actually failed.

Does boost:bad_lexical_cast let you access that string it had attempted to cast somehow? I could not seem to find anything in its definition except for some fields regarding type names, but maybe there's something I'm missing.

1

There are 1 answers

3
Richard Hodges On

if you have control of the code that calls lexical_cast, then you can use function try blocks to catch, wrap and re-throw the exception with extra information:

#include <boost/lexical_cast.hpp>
#include <string>
#include <stdexcept>
#include <exception>

struct conversion_error : std::runtime_error
{
  conversion_error(const std::string& name, const std::string& value)
    : std::runtime_error::runtime_error("converting " + name + " : " + value)
    , name(name)
    , value(value)
    {}

    const std::string name, value;
};

struct test
{

  void bar()
  {
    try { 
      foo(); 
    } catch(const conversion_error& e) { 
      std::cerr << e.what() << std::endl;
    }
  }

  void foo()
  try
  {
    i = boost::lexical_cast<int>(s);
  }
  catch(...)
  {
    std::throw_with_nested(conversion_error("s", s));
  }

  std::string s;
  int i;
};

int main()
{
  test a { "y", 0 };
  a.bar();
}