【问题标题】:c++ stacktrace from the function an exception is thrown?抛出异常的函数的c ++堆栈跟踪?
【发布时间】:2011-09-10 09:33:01
【问题描述】:

我可以利用 gcc 的回溯在程序的任何给定点获取堆栈跟踪,但我想从抛出异常时堆栈所在的任何帧获取跟踪,即在堆栈展开。

例如,下面的块

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

try {
  func();
}
catch ( std::exception ) {
  std::cout << print_trace();
  //do stuff
}

应该仍然能够以某种方式为 func() 保留一个框架。

这是asked before,但它涉及一个未处理的异常,该异常会终止程序并且可能没有给调用堆栈一个放松的机会?

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

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

【问题讨论】:

  • 如果您想知道异常是从哪里引发的,最好的办法是将该信息存储在异常中。

标签: c++ gcc exception-handling stack-trace callstack


【解决方案1】:

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

打印:

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

希望这会有所帮助!

【讨论】:

  • 差不多了,但还不完全...我只能指望从 boost 异常中获取跟踪,无法对 std::bad_alloc 等其他人做任何事情。太糟糕的跟踪不像 java 那样内置在标准异常类中!
  • @maldoz 不是每个人都需要回溯。但我同意它很有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
  • 1970-01-01
  • 2011-01-05
相关资源
最近更新 更多