js' blog

Backtraces for Exceptions
Created: 22.05.2013 21:42 UTC

I just implemented backtraces for exceptions. While at first, this does not seem to be worth the effort (especially if not using backtrace() from execinfo.h in order to be portable and not limited to platforms that aim to be compatible to glibc) as every debugger can do it, this has a huge advantage over using a debugger: It gets the location of where the exception was created rather than the location of where it was thrown!

But why does it make a difference if we get a backtrace when the exception is created or when it is thrown? Well, a common problem why many exceptions are hard to trace is that there is a lot of code that catches an exception, does some cleanup and then rethrows it. Using a debugger, you get the location of the last rethrow. But this is not where something actually went wrong! But if the backtrace is generated when the exception is created and then stored inside the exception, you can always get the backtrace of when the exception was created - which is what you're usually interested in.

And finally, to add even more convenience, the default handler for unhandled exceptions now also shows the backtrace from when the exception was created.

Edit: I had to partly revert it, as it turns out that __builtin_frame_address() just crashes on many platforms instead of returning NULL, like the documentation said. I should have expected this, considering that just crashing is what most of GCC's builtins do on many platforms… See here for details.