throw_with_nested.pass.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. // <exception>
  10. // class nested_exception;
  11. // template<class T> void throw_with_nested [[noreturn]] (T&& t);
  12. #include <exception>
  13. #include <cstdlib>
  14. #include <cassert>
  15. class A
  16. {
  17. int data_;
  18. public:
  19. explicit A(int data) : data_(data) {}
  20. friend bool operator==(const A& x, const A& y) {return x.data_ == y.data_;}
  21. };
  22. class B
  23. : public std::nested_exception
  24. {
  25. int data_;
  26. public:
  27. explicit B(int data) : data_(data) {}
  28. friend bool operator==(const B& x, const B& y) {return x.data_ == y.data_;}
  29. };
  30. int main()
  31. {
  32. {
  33. try
  34. {
  35. A a(3);
  36. std::throw_with_nested(a);
  37. assert(false);
  38. }
  39. catch (const A& a)
  40. {
  41. assert(a == A(3));
  42. }
  43. }
  44. {
  45. try
  46. {
  47. A a(4);
  48. std::throw_with_nested(a);
  49. assert(false);
  50. }
  51. catch (const std::nested_exception& e)
  52. {
  53. assert(e.nested_ptr() == nullptr);
  54. }
  55. }
  56. {
  57. try
  58. {
  59. B b(5);
  60. std::throw_with_nested(b);
  61. assert(false);
  62. }
  63. catch (const B& b)
  64. {
  65. assert(b == B(5));
  66. }
  67. }
  68. {
  69. try
  70. {
  71. B b(6);
  72. std::throw_with_nested(b);
  73. assert(false);
  74. }
  75. catch (const std::nested_exception& e)
  76. {
  77. assert(e.nested_ptr() == nullptr);
  78. const B& b = dynamic_cast<const B&>(e);
  79. assert(b == B(6));
  80. }
  81. }
  82. {
  83. try
  84. {
  85. int i = 7;
  86. std::throw_with_nested(i);
  87. assert(false);
  88. }
  89. catch (int i)
  90. {
  91. assert(i == 7);
  92. }
  93. }
  94. }