C++ display stack trace on exception

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.


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.


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.


如果您使用Boost 1.65或更高版本,则可以使用boost :: stacktrace:

#include <boost/stacktrace.hpp>

// ... somewhere inside the bar(int) function that is called recursively:
std::cout << boost::stacktrace::stacktrace();
链接地址: http://www.djcxy.com/p/86042.html

上一篇: 如何找到在C ++中抛出异常的位置?

下一篇: C ++显示堆栈跟踪异常