fork download
  1. #include <vector>
  2. #include <string>
  3.  
  4. struct stack_tracer {
  5. stack_tracer(const char* f) {stacktrace().push_back(f);}
  6. ~stack_tracer() {stacktrace().pop_back();}
  7. static const std::vector<const char*>& get_stack() {return stacktrace();}
  8. protected:
  9. stack_tracer(const stack_tracer& NOCOPY);
  10. stack_tracer&operator=(const stack_tracer& NOCOPY);
  11. static std::vector<const char*>& stacktrace() {
  12. static std::vector<const char*> stack;
  13. return stack;
  14. }
  15. };
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24. #include <iostream>
  25. #include <exception>
  26. #include <stdexcept>
  27.  
  28. class stack_aware_exception : public std::runtime_error {
  29. std::vector<const char*> stack;
  30. public:
  31. stack_aware_exception(const char* msg)
  32. :std::runtime_error(msg),
  33. stack(stack_tracer::get_stack())
  34. {}
  35. virtual ~stack_aware_exception() throw() {}
  36. const std::vector<const char*>& get_stack() const {return stack;}
  37. };
  38.  
  39. unsigned thing(unsigned i) {
  40. stack_tracer trace(__PRETTY_FUNCTION__);
  41. if (i==10)
  42. throw stack_aware_exception("message!");
  43. else if (i==0)
  44. return i;
  45. return thing(i-1);
  46. }
  47.  
  48. int Foo() {
  49. stack_tracer trace(__PRETTY_FUNCTION__);
  50. return thing(7) + thing(0) + thing(17);
  51. }
  52.  
  53. int main(int argc, char** argv) {
  54. stack_tracer trace(__PRETTY_FUNCTION__);
  55. try {
  56. Foo();
  57. } catch(const stack_aware_exception& exc) {
  58. std::cout << exc.what() << '\n';
  59. for(unsigned i=0; i<exc.get_stack().size(); ++i)
  60. std::cout << exc.get_stack()[i] << '\n';
  61. }
  62. return 0;
  63. }
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
message!
int main(int, char**)
int Foo()
unsigned int thing(unsigned int)
unsigned int thing(unsigned int)
unsigned int thing(unsigned int)
unsigned int thing(unsigned int)
unsigned int thing(unsigned int)
unsigned int thing(unsigned int)
unsigned int thing(unsigned int)
unsigned int thing(unsigned int)