Boost Exception

Adding Grouped Data to Exceptions

The code snippet below demonstrates how boost::tuple can be used to bundle the name of the function that failed, together with the reported errno so that they can be added to exception objects more conveniently together:

#include <boost/exception/info_tuple.hpp>
#include <boost/shared_ptr.hpp>
#include <stdio.h>
#include <string>
#include <errno.h>

typedef boost::error_info<struct tag_file_name,std::string> file_name_info;
typedef boost::error_info<struct tag_function,char const *> function_info;
typedef boost::error_info<struct tag_errno,int> errno_info;
typedef boost::tuple<function_info,errno_info> clib_failure;

class file_open_error: public boost::exception { };

boost::shared_ptr<FILE>
file_open( char const * name, char const * mode )
    {
    if( FILE * f=fopen(name,mode) )
        return boost::shared_ptr<FILE>(f,fclose);
    else
        throw file_open_error() <<
            file_name_info(name) <<
            clib_failure("fopen",errno);
    }

Note that the members of a boost::tuple are stored separately in exception objects; they can only be retrieved individually, using get_error_info().

See also: