c ++ stacktrace从函数抛出异常?

mal*_*doz 5 c++ gcc callstack exception-handling stack-trace

我可以利用gcc的backtrace在程序的任何给定点获得堆栈跟踪,但是我想从抛出异常时堆栈所处的任何帧中获取跟踪,即在堆栈展开之前.

例如,以下块

func() {
  throw std::exception();
}

try {
  func();
}
catch ( std::exception ) {
  std::cout << print_trace();
  //do stuff
}
Run Code Online (Sandbox Code Playgroud)

应该还能以某种方式为func()保留一个框架.

以前曾经问过这个问题,但它涉及到一个未处理的异常会终止该程序,并且可能没有给callstack一个放松的机会?

有没有办法做到这一点,同时仍能正常捕获和处理异常?

可能有一种方法,比如为所有异常设置处理程序,除了生成跟踪并重新抛出异常之外什么都不做.理想情况下,我应该能够在Exception类构造函数中生成跟踪,但是在这里我不一定能控制可能遇到的异常.

BЈо*_*вић 5

您可能对正在开发的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)

希望这可以帮助!