C++ exceptions with stack traces

Crud. I’ve spent some time trying to figure out a portable way to do this, and it’s not simple. At all. If you don’t care about portability and you use win32 or linux, then there are simple solutions because the OS maintains a list of symbols and can give them to user applications at any time.

My first thought was that I could write a macro, called “THROW” or something like that, that would help keep track of the frames in the stack trace. Not only is that not as simple as it sounds, it also only works for exceptions that are thrown and re-thrown all the way back up to main(), which doesn’t really solve the issue for me.

My second attempt involved templates, because templates are supposed to replace a lot of functionality that macros once provided. It looked something like this: template class st_exception : public std::runtime_error; int f() { throw st_exception<__file__ , __LINE__, __func__>("message"); }

Not only would this be very cumbersome to use, it was tricky to implement. Even after I got the template voodoo worked out (hint: you can’t pass a string literal as a template parameter), it still didn’t even work.

My next attempt will try to exploit information available in the C++ ABI. This way (assuming it works), I can implement exceptions with stack information and have it be portable too.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>