2012-05-22 102 views
1

我有一个从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。有人能告诉我如何抛出这个异常并获取文件,函数等数据吗? 。struct ConfigurationException : virtual std::exception, virtual boost::exception

  • 渔获量引用::(我应该从两个std::exceptionboost::exception几乎说显然是throw ConfigurationException("some title", "some message");工作正常

  • 回答

    2
    1. 导出。catch (const std::exception& e)
    2. 不要把GUI逻辑异常将它放入异常处理程序(例如catch块)
    3. 考虑使用error_info来附加附加信息(如标题和消息)

    而且一般来说,将Qt与例外混合时要小心。

    +0

    感谢您的解决方案。您是否可以详细说明将Qt与异常混合的观点?你能否提出一种更好的方式来部署一条消息来通知用户损坏的配置文件? –

    0

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

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