Getting the backtrace from the catch block

后端 未结 3 1669
悲&欢浪女
悲&欢浪女 2020-12-09 10:23

I am using backtrace to get the information from where the exception is thrown. In the constructor of my exception, I am storing the backtrace in a std::string, and in the c

相关标签:
3条回答
  • 2020-12-09 11:02

    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);
        }
    }
    

    Prints:

    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
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-09 11:11

    Do the classes in question share a common base you can edit?

    Otherwise, I provided a wonderful but terribly underappreciated answer at How can some code be run each time an exception is thrown in a Visual C++ program? ;-P Some others opined too.

    0 讨论(0)
  • 2020-12-09 11:14

    I don't think so. When executons stops in catch block the stack is unwound, and all that has happened before is not in stack anymore.

    0 讨论(0)
提交回复
热议问题