gpt4 book ai didi

c++ - 子类化 boost 异常

转载 作者:行者123 更新时间:2023-11-30 04:27:45 25 4
gpt4 key购买 nike

我有一个继承自 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"); 工作正常。

最佳答案

  1. std::exceptionboost::exception 派生 virtually:struct ConfigurationException :虚拟 std::exception,虚拟 boost::exception.
  2. 通过 const 引用捕获:catch (const std::exception& e)
  3. 不要将 GUI 逻辑放在异常构造函数中。将其放在异常处理程序中(即 catch block )。
  4. 考虑使用 error_info 附加其他信息(例如您的标题和消息)。

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

关于c++ - 子类化 boost 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10699367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com