throwing_st.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright Antony Polukhin, 2016-2019.
  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. #include <boost/config.hpp>
  7. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  8. //[getting_started_class_traced
  9. #include <boost/stacktrace.hpp>
  10. #include <boost/exception/all.hpp>
  11. typedef boost::error_info<struct tag_stacktrace, boost::stacktrace::stacktrace> traced;
  12. //]
  13. //[getting_started_class_with_trace
  14. template <class E>
  15. void throw_with_trace(const E& e) {
  16. throw boost::enable_error_info(e)
  17. << traced(boost::stacktrace::stacktrace());
  18. }
  19. //]
  20. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  21. BOOST_NOINLINE void oops(int i);
  22. BOOST_NOINLINE void foo(int i);
  23. BOOST_NOINLINE void bar(int i);
  24. #include <stdexcept>
  25. BOOST_NOINLINE void oops(int i) {
  26. //[getting_started_throwing_with_trace
  27. if (i >= 4)
  28. throw_with_trace(std::out_of_range("'i' must be less than 4 in oops()"));
  29. if (i <= 0)
  30. throw_with_trace(std::logic_error("'i' must be greater than zero in oops()"));
  31. //]
  32. foo(i);
  33. std::exit(1);
  34. }
  35. #include <boost/array.hpp>
  36. BOOST_NOINLINE void bar(int i) {
  37. boost::array<int, 5> a = {{0, 0, 0, 0, 0}};
  38. if (i < 5) {
  39. if (i >= 0) {
  40. foo(a[i]);
  41. } else {
  42. oops(i);
  43. }
  44. }
  45. std::exit(2);
  46. }
  47. BOOST_NOINLINE void foo(int i) {
  48. bar(--i);
  49. }
  50. #include <iostream>
  51. int main() {
  52. //[getting_started_catching_trace
  53. try {
  54. foo(5); // testing assert handler
  55. } catch (const std::exception& e) {
  56. std::cerr << e.what() << '\n';
  57. const boost::stacktrace::stacktrace* st = boost::get_error_info<traced>(e);
  58. if (st) {
  59. std::cerr << *st << '\n'; /*<-*/ return 0; /*->*/
  60. } /*<-*/ return 3; /*->*/
  61. }
  62. //]
  63. return 5;
  64. }