代码之家  ›  专栏  ›  技术社区  ›  BЈовић

从catch块获取回溯

  •  15
  • BЈовић  · 技术社区  · 14 年前

    我在用 backtrace 从引发异常的位置获取信息。在异常的构造函数中,我将回溯存储在std::string中,在该类型异常的catch块中,我将打印此回溯。

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

    3 回复  |  直到 14 年前
        1
  •  8
  •   Dialecticus    14 年前

    我不这么认为。当executons在catch块中停止时,堆栈将被解除,以前发生的所有事情都不再在堆栈中。

        2
  •  9
  •   Daniel Lidström    14 年前

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

    希望这有帮助!

        3
  •  1
  •   Community CDub    8 年前

    所讨论的类是否共享可以编辑的公共基础?

    否则,我在 How can some code be run each time an exception is thrown in a Visual C++ program? 其他一些人也这么认为。