Andrew Grant’s answer does not help getting a stack trace of the throwing function, at least not with GCC, because a throw statement does not save the current stack trace on its own, and the catch handler won’t have access to the stack trace at that point any more.
The only way – using GCC – to solve this is to make sure to generate a stack trace at the point of the throw instruction, and save that with the exception object.
This method requires, of course, that every code that throws an exception uses that particular Exception class.
Update 11 July 2017: For some helpful code, take a look at cahit beyaz’s answer, which points to http://stacktrace.sourceforge.net – I haven’t used it yet but it looks promising.
Update 29 July 2023: Stack trace libraries as of July 2023:
- C++23
<stacktrace>: C++23 will introduce<stacktrace>, which some standard library implementations already support or partially support. - boost stacktrace: Reference implementation for
<stacktrace>proposed by the authors. It is feature-full but requires various configuration and dependencies. - backward-cpp: A widely used library and provides a lot of information, including code snippets for each frame. Depending on your system it has various configuration and dependencies. It supports most platforms other than mingw.
- cpptrace: A newer C++ stack trace library that is simple, portable, and self-contained.