2

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

0

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();
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • With due respect - if I had access to `s` I would not ask this question... the point is that I don't have access to it. – einpoklum Apr 13 '16 at 16:14
  • @einpoklum forgive me, I misunderstood the question. – Richard Hodges Apr 13 '16 at 17:11
  • 1
    There's nothing to forgive, you were trying to help. Although this is SO, which means you're supposed to be barraged with negative feedback, I certainly appreciate people who take the time to answer my questions :-) – einpoklum Apr 13 '16 at 17:13