从catch块获取回溯

BЈо*_*вић 15 c++ linux exception-handling backtrace

我正在使用backtrace从抛出异常的位置获取信息.在我的异常的构造函数中,我将回溯存储在std :: string中,并且在catch块中为此类型的异常存储,我正在打印此回溯.

但我想知道,是否有可能以某种方式在catch块中为其他异常类型获得相同的回溯?

Dan*_*röm 9

您可能对正在开发的Boost库感兴趣:Portable Backtrace.例:

#include <boost/backtrace.hpp>
#include <iostream>

int foo()
{
    throw boost::runtime_error("My Error");
    return 10;
}

int bar()
{
    return foo()+20;
}


int main()
{
    try {
        std::cout << bar() << std::endl;
    }
    catch(std::exception const &e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << boost::trace(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

打印:

My Error
0x403fe1: boost::stack_trace::trace(void**, int) + 0x1b in ./test_backtrace
0x405451: boost::backtrace::backtrace(unsigned long) + 0x65 in ./test_backtrace
0x4054d2: boost::runtime_error::runtime_error(std::string const&) + 0x32 in ./test_backtrace
0x40417e: foo() + 0x44 in ./test_backtrace
0x40425c: bar() + 0x9 in ./test_backtrace
0x404271: main + 0x10 in ./test_backtrace
0x7fd612ecd1a6: __libc_start_main + 0xe6 in /lib/libc.so.6
0x403b39: __gxx_personality_v0 + 0x99 in ./test_backtrace
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 也许您可以单独下载并单独使用它.然后当/如果它成为官方Boost你可能能够切换/升级.祝好运! (2认同)

Dia*_*cus 8

我不这么认为.当执行器在catch块中停止时,堆栈被解开,之前发生的所有事情都不再存在于堆栈中.