When using boost::exception
, what is the preferred way to know what data the exception is carrying? In the boost documentation the following example is given:
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";
}
This seems to be a bit awkward, especially if the exception bubbled through a lot of layers and has a load of metadata theoretically available. So I guess it makes sense to document what the possible error infos are for each exception class. Then I probably also need documentation for some functions, about what information might be in the exceptions. In the end I feel like I have the exact same structure in documentation, as I would have in code if I just used something like the following struct:
struct FileException {
string* filename; // NULL or string
}
I could then change this information in a catch block:
catch (FileException& e) {
e.filename = filename;
throw;
}
This simple way I would get around most of the documentation, and profit from all of the safety (e.g. not trying to get filenames from MathException
). Yet people use boost. Is there a big advantage of the dynamic approach that I'm missing? How do you document the error infos in your code?
From a very high level, you can refer to the diagnostic information of that exception: http://www.boost.org/doc/libs/1_51_0/libs/exception/doc/diagnostic_information.html
This will print everything the exception carries (and a little more). I'm not sure if there is a way to get at all of the internal stuff individually...
From the examples:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With