我有一个继承自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");
工作正常。
答案 0 :(得分:2)
std::exception
和boost::exception
虚拟:struct ConfigurationException : virtual std::exception, virtual boost::exception
。{/ li>
catch (const std::exception& e)
。catch
块)。error_info
附加其他信息(例如您的标题和消息)。一般情况下,将Qt与异常混合时要小心。
答案 1 :(得分: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&amp; e)。