I want to have a way to report the stack trace to the user if an exception is thrown. What is the best way to do this? Does it take huge amounts of extra code?
To answer questions:
I'd like it to be portable if possible. I want information to pop up, so the user can copy the stack trace and email it to me if an error comes up.
Cpp-tool ex_diag - easyweight, multiplatform, minimal resource using, simple and flexible at trace.
It depends which platform.
On GCC it's pretty trivial, see this post for more details.
On MSVC then you can use the StackWalker library that handles all of the underlying API calls needed for Windows.
You'll have to figure out the best way to integrate this functionality into your app, but the amount of code you need to write should be minimal.
I would like to add a standard library option (i.e. cross-platform) how to generate exception backtraces, which has become available with C++11:
Use
std::nested_exception
andstd::throw_with_nested
This won't give you a stack unwind, but in my opinion the next best thing. It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.
Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:
on linux with g++ check out this lib
https://sourceforge.net/projects/libcsdbg
it does all the work for you
Unix: backtrace
Mac: backtrace
Windows: CaptureBackTrace
On Windows, check out BugTrap. Its not longer at the original link, but its still available on CodeProject.