【问题标题】:subclassing boost exception子类化提升异常
【发布时间】:2012-05-22 09:32:29
【问题描述】:

我有一个继承自boost::exception 的自定义异常类,如下所示:

class ConfigurationException : public boost::exception
{
public:
    ConfigurationException(const std::string & title, const std::string & message) {
        QMessageBox box(QMessageBox::Critical, QString::fromStdString(title), QString::fromStdString( parse(message) ), QMessageBox::Ok);
        box.exec();
    }
}

它可以从这样的代码中调用:

try {
   // Do some stuff here
} catch (std::exception e) {
    BOOST_THROW_EXCEPTION( ConfigurationException("Configuration Error", e.what()) );
}

但是,当我尝试编译时,我得到了错误

Libs\boost\include\boost/throw_exception.hpp(58): error C2664:'boost::throw_exception_assert_compatibility' : cannot convert parameter 1 from 'const ConfigurationException' to 'const std::exception &'
          Reason: cannot convert from 'const ConfigurationException' to 'const std::exception'
          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
          Libs\boost\include\boost/throw_exception.hpp(85) : see reference to function template instantiation 'void boost::throw_exception<E>(const E &)' being compiled
          with
          [
              E=ConfigurationException
          ]
          src\ConfigurationReader.cpp(81) : see reference to function template instantiation 'void boost::exception_detail::throw_exception_<ConfigurationException>(const E &,const char *,const char *,int)' being compiled
          with
          [
              E=ConfigurationException
          ]

我不太确定为什么它试图将我的异常转换为std::exception。有人能告诉我如何抛出这个异常并获取文件、函数等数据吗? (我应该说throw ConfigurationException("some title", "some message"); 工作正常。

【问题讨论】:

    标签: c++ exception boost subclass


    【解决方案1】:
    1. 派生自std::exceptionboost::exception 实际上struct ConfigurationException : virtual std::exception, virtual boost::exception
    2. 通过 const 引用捕获:catch (const std::exception&amp; e)
    3. 不要将 GUI 逻辑放在异常构造函数中。将其放入异常处理程序(即catch 块)。
    4. 考虑使用error_info 附加其他信息(例如您的标题和消息)。

    一般来说,将 Qt 与异常混合使用时要小心。

    【讨论】:

    • 感谢您的解决方案。您能否详细说明您关于将 Qt 与异常混合的观点?您能否建议一种更好的方法来部署消息以通知用户配置文件损坏?
    【解决方案2】:

    BOOST_THROW_EXCEPTION 调用 boost::throw_exception,它要求异常对象派生自 std::exception(参见 www.boost.org/doc/libs/release/libs/exception/doc/throw_exception.html)。编译错误强制执行该要求。

    另一件事,通过引用捕获异常。不要 catch(std::exception e),而是 catch(std::exception & e)。

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 2011-04-02
      • 2022-01-02
      • 1970-01-01
      • 2011-06-01
      • 2021-03-30
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多