# Boost Exception

## Transporting of Arbitrary Data to the Catch Site

All exception types that derive from boost::exception can be used as type-safe containers of arbitrary data objects, while complying with the no-throw requirements (15.5.1) of the ANSI C++ standard for exception types.

When exceptions derive from boost::exception, arbitrary data can be added to exception objects:

- At the point of the throw;
- At a later time as exceptions bubble up the call stack.

### Adding of Arbitrary Data at the Point of the Throw

The following example demonstrates how errno can be stored in exception objects using Boost Exception:

    #include <boost/exception/all.hpp>
    #include <iostream>

    typedef boost::error_info<struct tag_my_info,int> my_info; //(1)

    struct my_error: virtual boost::exception, virtual std::exception { }; //(2)

    void
    f()
        {
        throw my_error() << my_info(42); //(3)
        }

First, we instantiate the error_info template using a unique identifier -- tag_my_info, 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 my_info value can be recovered at a later time like this:

    // ...continued

    void
    g()
        {
        try
            {
            f();
            }
        catch(
        my_error & x )
            {
            if( int const * mi=boost::get_error_info<my_info>(x) )
                std::cerr << "My info: " << *mi;
            }
        }

The get_error_info function template is instantiated with the typedef from (1), and is passed an exception object of a polymorphic type. If the exception object contains the requested value, err will point to it; otherwise a null pointer is returned.

### Adding of Arbitrary Data to Active Exception Objects

Sometimes the throw site does not have all the information that is needed at the catch site to make sense of what went wrong. Let's say we have an exception type file_read_error, which takes a file name in its constructor. Consider the following function:

    void
    file_read( FILE * f, void * buffer, size_t size )
        {
        if( size!=fread(buffer,1,size,f) )
            throw file_read_error(????);
        }

How can the file_read function pass a file name to the exception type constructor? All it has is a FILE handle.

Using boost::exception allows us to free the file_read function from the burden of storing the file name in exceptions it throws:

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

    struct file_read_error: virtual boost::exception { };

    void
    file_read( FILE * f, void * buffer, size_t size )
        {
        if( size!=fread(buffer,1,size,f) )
            throw file_read_error() << boost::errinfo_errno(errno);
        }

If file_read detects a failure, it throws an exception which contains the information that is available at the time, namely the errno. Other relevant information, such as the file name, can be added in a context higher up the call stack, where it is known naturally:

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

    boost::shared_ptr<FILE> file_open( char const * file_name, char const * mode );
    void file_read( FILE * f, void * buffer, size_t size );

    void
    parse_file( char const * file_name )
        {
        boost::shared_ptr<FILE> f = file_open(file_name,"rb");
        assert(f);
        try
            {
            char buf[1024];
            file_read( f.get(), buf, sizeof(buf) );
            }
        catch(
        boost::exception & e )
            {
            e << boost::errinfo_file_name(file_name);
            throw;
            }
        }

The above function is (almost) exception-neutral -- if an exception is emitted by any function call within the try block, parse_file does not need to do any real work, but it intercepts any boost::exception object, stores the file name, and re-throws using a throw-expression with no operand (15.1.6). The rationale for catching any boost::exception object is that the file name is relevant to any failure that occurs in parse_file, even if the failure is unrelated to file I/O.

### 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/exception/errinfo_file_name.hpp>
    #include <boost/exception/errinfo_api_function.hpp>
    #include <boost/exception/errinfo_errno.hpp>
    #include <boost/shared_ptr.hpp>
    #include <stdio.h>
    #include <string>
    #include <errno.h>

    typedef boost::tuple<boost::errinfo_api_function,boost::errinfo_errno> clib_failure;

    struct file_open_error: virtual 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() <<
                boost::errinfo_file_name(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:

Boost Exception
Integrating Boost Exception in Existing Exception Class Hierarchies