2012-05-22 104 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)。