Boost logo

Boost :

From: Atry (pop.atry_at_[hidden])
Date: 2007-04-20 13:04:40


Java programs are easy to debug, one who catch an exception can print
the stack trace, and when it crash, it would print the stack, too. It is
useful, so I wrote some code of stack_trace for C++, see the sample below:

/***** sample.cpp *****/
#include <boost/stack_trace.hpp>
#include <iostream>
#include <sstream>
using namespace boost;
using namespace std;

class exception_with_stack_trace : public exception
{
private:
    std::string what_;
public:
    exception_with_stack_trace(const char* file, unsigned int line,
const char* func)
    {
        stringstream ss;
        ss << "exception occurred at " << func << " (" << file << ":" <<
line << ")\n";
        vector<stack_trace::element const *> const & st =
stack_trace::get();
        for(size_t i = st.size(); --i != 0; )
        {
            ss << "\tfrom " << st[i]->tag() << " (" << st[i]->file() <<
":" << st[i]->line() << ")\n";
        }
        what_ = ss.str();
    }
    virtual exception_with_stack_trace::~exception_with_stack_trace()
throw (){}
    virtual const char * what() const throw ()
    {
        return what_.c_str();
    }
};

void foo(int a)
{
    BOOST_STACK_TRACK_CALL;
    cout << stack_trace::to_string() << endl;
    if(a == 1)
    {
        throw exception_with_stack_trace(__FILE__, __LINE__, __FUNCTION__);
    }

}
void foo()
{ BOOST_STACK_TRACK_CALL;
    foo(0);
    foo(1);
    cout << stack_trace::to_string() << endl;
}
void bar()
{ BOOST_STACK_TRACK_CALL;
    foo();
    cout << stack_trace::to_string() << endl;
}

int main()
{
    BOOST_STACK_TRACK_CALL;
    try
    {
        BOOST_STACK_TRACK_TAG("try");
        foo();
        cout << stack_trace::to_string() << endl;
        bar();
        cout << stack_trace::to_string() << endl;
    }
    catch(exception& e)
    {
        cerr << e.what() << endl;
    }
}
/***** sample.cpp *****/

And run it to print below:

1> stdout
sample.cpp 54 main
sample.cpp 57 try
sample.cpp 41 foo
sample.cpp 32 foo

sample.cpp 54 main
sample.cpp 57 try
sample.cpp 41 foo
sample.cpp 32 foo

2> stderr
exception occurred at foo (sample.cpp:36)
        from foo (sample.cpp:32)
        from foo (sample.cpp:41)
        from try (sample.cpp:57)


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk