C++ display stack trace on exception

2018-12-31 23:58发布

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.

14条回答
忆尘夕之涩
2楼-- · 2019-01-01 00:33

Cpp-tool ex_diag - easyweight, multiplatform, minimal resource using, simple and flexible at trace.

查看更多
美炸的是我
3楼-- · 2019-01-01 00:34

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.

查看更多
唯独是你
4楼-- · 2019-01-01 00:36

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 and std::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:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
查看更多
泛滥B
5楼-- · 2019-01-01 00:40

on linux with g++ check out this lib

https://sourceforge.net/projects/libcsdbg

it does all the work for you

查看更多
临风纵饮
6楼-- · 2019-01-01 00:42
孤独总比滥情好
7楼-- · 2019-01-01 00:43

On Windows, check out BugTrap. Its not longer at the original link, but its still available on CodeProject.

查看更多
登录 后发表回答