获取 boost::exception 的 what() 消息
Get the what() message of boost::exception
在下面的代码中,我想获取 boost::exception 的what()
消息。
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/exception/diagnostic_information.hpp>
int main(void)
{
try
{
int i(boost::lexical_cast<int>("42X"));
}
catch (boost::exception const &e)
{
std::cout << "Exception: " << boost::diagnostic_information_what(e) << "n";
}
return 0;
}
当我运行它时,我收到消息:
Exception: Throw location unknown (consider using BOOST_THROW_EXCEPTION)
Dynamic exception type: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >
但是当我没有捕获异常时,shell 输出:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
what(): bad lexical cast: source type value could not be interpreted as target
[1] 8744 abort ./a.out
我想要那条信息:bad lexical cast: source type value could not be interpreted as target
;但我找不到拥有它的方法。提升异常系统对我来说是个谜。
如何获得此消息?
编辑:提升::异常没有what()
方法。那么,由于这不是std::exception
,外壳如何写std::exception::what: bad lexical cast: source type value could not be interpreted as target
呢?
捕获为bad_lexical_cast
以使用方法what()
:
catch (const boost::bad_lexical_cast& e)
{ // ^^^^^^^^^^^^^^^^^^^^^^^
std::cout << "Exception: " << e.what() << "n";
// ^^^^^^^^
}
它将显示Exception: bad lexical cast: source type value could not be interpreted as target
来自diagnostic_information_what
参考:
diagnostic_information_what函数旨在从用户定义的 std::exception::what() 覆盖中调用。
该函数不应该给你来自what()
函数的消息,它应该在what()
函数中用于创建要返回的消息。
然后继续,从boost::lexical_cast
参考:
如果转换不成功,则会引发bad_lexical_cast异常。
那么让我们来看看bad_lexical_cast
:
class bad_lexical_cast : public std::bad_cast
它继承自标准std::bad_cast
继承自具有what()
成员函数的std::exception
。
所以解决方案是捕获boost::bad_lexical_cast
(或std::exception
),而不是完全不涉及boost::exception
。
- boost::进程间消息队列引发错误
- 在线编译器中的分段C++没有打印消息
- C++错误消息*成员参考.**初学者*
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何通过参数抛出错误消息
- 从服务器传输到客户端的消息不会出现
- ROS2 动态消息模板
- 什么是 std::exception::what() 以及为什么要使用它?
- C++秘密消息学校作业
- glad 导致 glfwSwapBuffers 返回错误消息
- C++入门 5 版:类消息和文件夹
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 由于无效的 ValidateRgn() 子窗口不会收到WM_PAINT消息
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++/pthread/join 错误消息的含义 "what(): Invalid argument"
- 获取 boost::exception 的 what() 消息