• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright Antony Polukhin, 2016-2020.
2 //
3 // Distributed under the Boost Software License, Version 1.0. (See
4 // accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
6 
7 #include <boost/config.hpp>
8 
9 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
10 
11 //[getting_started_class_traced
12 #include <boost/stacktrace.hpp>
13 #include <boost/exception/all.hpp>
14 
15 typedef boost::error_info<struct tag_stacktrace, boost::stacktrace::stacktrace> traced;
16 //]
17 
18 //[getting_started_class_with_trace
19 template <class E>
throw_with_trace(const E & e)20 void throw_with_trace(const E& e) {
21     throw boost::enable_error_info(e)
22         << traced(boost::stacktrace::stacktrace());
23 }
24 //]
25 
26 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
27 
28 BOOST_NOINLINE void oops(int i);
29 BOOST_NOINLINE void foo(int i);
30 BOOST_NOINLINE void bar(int i);
31 
32 #include <stdexcept>
oops(int i)33 BOOST_NOINLINE void oops(int i) {
34     //[getting_started_throwing_with_trace
35     if (i >= 4)
36         throw_with_trace(std::out_of_range("'i' must be less than 4 in oops()"));
37     if (i <= 0)
38         throw_with_trace(std::logic_error("'i' must be greater than zero in oops()"));
39     //]
40     foo(i);
41     std::exit(1);
42 }
43 
44 #include <boost/array.hpp>
bar(int i)45 BOOST_NOINLINE void bar(int i) {
46     boost::array<int, 5> a = {{0, 0, 0, 0, 0}};
47     if (i < 5) {
48         if (i >= 0) {
49             foo(a[i]);
50         } else {
51             oops(i);
52         }
53     }
54     std::exit(2);
55 }
56 
foo(int i)57 BOOST_NOINLINE void foo(int i) {
58     bar(--i);
59 }
60 
61 #include <iostream>
main()62 int main() {
63 
64     //[getting_started_catching_trace
65     try {
66         foo(5); // testing assert handler
67     } catch (const std::exception& e) {
68         std::cerr << e.what() << '\n';
69         const boost::stacktrace::stacktrace* st = boost::get_error_info<traced>(e);
70         if (st) {
71             std::cerr << *st << '\n'; /*<-*/ return 0; /*->*/
72         } /*<-*/ return 3; /*->*/
73     }
74     //]
75 
76     return 5;
77 }
78 
79