Boost logo

Boost Users :

Subject: [Boost-users] Exception: adding diagnostic information from a dtor?
From: Michael Schuerig (michael.lists_at_[hidden])
Date: 2011-06-14 17:45:14


The FAQ for boost exception contain this example snippet for adding
further information to an exception while the call stack is unwound

catch( boost::exception & e )
    {
    e << foo_info(foo);
    throw; //Okay, re-throwing the original exception object.
    }

I like that this possible, but I think the resulting code is somewhat
tedious:

void foo(const string& file_name) {
    try {
        do_something_fallible(file_name);
    } catch( boost::exception & e ) {
        e << boost::errinfo_file_name(file_name);
        throw;
    }
}

I'd rather write it like this:

void foo(const string& file_name) {
    diagnostic<errinfo_file_name>(file_name);
    do_something_fallible(file_name);
}

My first, non-generic attempt fails:

class diagnostic {
public:
    explicit diagnostic(const string& file_name)
        : file_name_(file_name) {}
    ~diagnostic() {
        if ( boost::exception_ptr e = boost::current_exception() ) {
             *e << boost::errinfo_file_name(file_name_.c_str());
        }
    }
private:
    const string file_name_;
};

The requirements for boost::current_exception() state that it may only
be called inside a catch block, therefore the code above is illegal to
begin with. Ignoring that, operator<< doesn't appear to be suitably
overloaded for this use, anyway.

Now, I'm wondering, is what I'm trying to achieve a bad idea? If not, is
there another way to do it?

Michael

-- 
Michael Schuerig
mailto:michael_at_[hidden]
http://www.schuerig.de/michael/

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net