【问题标题】:When catching a boost::bad_lexical_cast, can I access the string/token which was to be cast?捕获 boost::bad_lexical_cast 时,我可以访问要转换的字符串/令牌吗?
【发布时间】:2016-08-04 17:45:16
【问题描述】:

我正在运行的代码在转换一系列标记时可能会抛出 boost:bad_lexical_cast - 但我无法进入代码并“将标记放在一边”,因此我可以找出实际失败的转换。

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

【问题讨论】:

  • 如果你能展示一些代码,我会告诉你我将如何重构它以允许它同时仍然可读。
  • @RichardHodges: try { foo(); } catch(boost::bad_lexical_cast& e) { /* what to do here? */ }

标签: c++ boost exception-handling lexical-cast


【解决方案1】:

如果您可以控制调用 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();
}

【讨论】:

  • 恕我直言-如果我可以访问s,我不会问这个问题...关键是我无法访问它。
  • @einpoklum 原谅我,我误解了这个问题。
  • 没什么可原谅的,你是想帮忙的。虽然这是这样,这意味着你应该受到负面反馈的抨击,但我当然感谢那些花时间回答我问题的人:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2013-02-09
  • 1970-01-01
  • 2020-05-02
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多