c ++ stacktrace从函数抛出异常? [英] c++ stacktrace from the function an exception is thrown?

查看:393
本文介绍了c ++ stacktrace从函数抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can make use of gcc's backtrace to obtain a stack trace at any given point of a program, but I would like to obtain the trace from whatever frame the stack was in at the time an exception is thrown, ie prior to the stack unwinding.

例如,以下块

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

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

应该还能保留框架for func()不知何故。

ought to still be able to retain a frame for func() somehow.

这是之前,但它涉及一个未处理的异常,将终止程序,可能没有给callstack有机会放松?

This has been asked before, but it involved an unhandled exception that would terminate the program and presumably didn't give the callstack a chance to unwind?

有没有办法做到这一点,但仍然能够抓住并正常处理异常?

Is there a way to do this while still being able to catch and handle the exception normally?

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

There could be an approach like having a handler for all exceptions that do nothing but generate the trace and re-throw the exceptions. Ideally I should be able to generate traces within Exception class constructors, but here I do not necessarily have control over the exceptions that could be encountered.

推荐答案

您可能对正在开发的Boost图书馆感兴趣:便携式回溯。示例:

You might be interested in a Boost library under development: Portable Backtrace. Example:

#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

希望这有帮助!

这篇关于c ++ stacktrace从函数抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆