gpt4 book ai didi

c++ - boost 异常的错误信息

转载 作者:可可西里 更新时间:2023-11-01 18:39:42 26 4
gpt4 key购买 nike

使用 boost::exception 时,了解异常携带哪些数据的首选方法是什么?在boost documentation给出了以下示例:

catch( io_error & e )
{
std::cerr << "I/O Error!\n";

if( std::string const * fn=get_error_info<file_name>(e) )
std::cerr << "File name: " << *fn << "\n";

if( int const * c=get_error_info<errno_code>(e) )
std::cerr << "OS says: " << strerror(*c) << "\n";
}

这似乎有点尴尬,特别是如果异常冒泡了很多层并且理论上有大量可用的元数据。所以我想记录每个异常类的可能错误信息是有意义的。然后我可能还需要一些功能的文档,关于异常中可能包含哪些信息。最后,我觉得我在文档中拥有完全相同的结构,如果我只使用类似以下结构的代码,我就会在代码中拥有完全相同的结构:

struct FileException {
string* filename; // NULL or string
}

然后我可以在 catch block 中更改此信息:

catch (FileException& e) {
e.filename = filename;
throw;
}

通过这种简单的方法,我可以绕过大部分文档,并从所有安全性中获益(例如,不尝试从 MathException 获取文件名)。然而人们使用boost。我缺少的动态方法有很大的优势吗?您如何记录代码中的错误信息?

最佳答案

从一个非常高的层次,你可以引用那个异常的诊断信息: http://www.boost.org/doc/libs/1_51_0/libs/exception/doc/diagnostic_information.html

这将打印异常携带的所有内容(以及更多)。我不确定是否有办法单独获取所有内部内容...

来自示例:

example_io.cpp(70): Throw in function class boost::shared_ptr<struct _iobuf> __cdecl my_fopen(const char *,const char *)
Dynamic exception type: class boost::exception_detail::clone_impl<struct fopen_error>
std::exception::what: example_io error
[struct boost::errinfo_api_function_ *] = fopen
[struct boost::errinfo_errno_ *] = 2, "No such file or directory"
[struct boost::errinfo_file_name_ *] = tmp1.txt
[struct boost::errinfo_file_open_mode_ *] = rb

关于c++ - boost 异常的错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12712764/

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