当捕获boost::bad_exical_cast时,我可以访问要强制转换的字符串/令牌吗

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

本文关键字:转换 字符串 令牌 访问 boost bad exical cast 我可以      更新时间:2023-10-16

我正在运行的代码可能会在强制转换一系列令牌时抛出boost:bad_lexical_cast,但我不能进入代码并"将令牌放在一边",这样我就可以找出实际失败的强制转换。

boost:bad_lexical_cast是否允许您访问它试图以某种方式强制转换的字符串?我似乎在它的定义中找不到任何东西,除了一些关于类型名的字段,但也许我缺少了一些东西。

如果您可以控制调用lexical_cast的代码,那么您可以使用函数try块来捕获、包装和重新抛出异常,并提供额外信息:

#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();
}