The following example demonstrates how errno can be stored in exception objects using Boost Exception:
#include <boost/exception.hpp> #include <errno.h> #include <iostream> typedef boost::error_info<struct tag_errno,int> errno_info; //(1) class my_error: public boost::exception, public std::exception { }; //(2) void f() { throw my_error() << errno_info(errno); //(3) }
First, we instantiate the error_info template using a unique identifier -- tag_errno, and the type of the info it identifies -- int. This provides compile-time type safety for the various values stored in exception objects.
Second, we define class my_error, which derives from boost::exception.
Finally, (3) illustrates how the typedef from (1) can be used with operator<<() to store values in exception objects at the point of the throw.
The stored errno value can be recovered at a later time like this:
// ...continued
void
g()
{
try
{
f();
}
catch(
my_error & x )
{
if( boost::shared_ptr<int const> err=boost::get_error_info<errno_info>(x) )
std::cerr << "Error code: " << *err;
}
}
The get_error_info() function template is instantiated with the typedef from (1), and is passed an exception object of any type that derives publicly from boost::exception. If the exception object contains the requested value, the returned shared_ptr will point to it; otherwise an empty shared_ptr is returned.