throw_with_nested.pass.cpp 2.3 KB

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