throw_with_nested.pass.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // UNSUPPORTED: libcpp-no-exceptions
  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. #include "test_macros.h"
  16. class A
  17. {
  18. int data_;
  19. public:
  20. explicit A(int data) : data_(data) {}
  21. friend bool operator==(const A& x, const A& y) {return x.data_ == y.data_;}
  22. };
  23. class B
  24. : public std::nested_exception
  25. {
  26. int data_;
  27. public:
  28. explicit B(int data) : data_(data) {}
  29. friend bool operator==(const B& x, const B& y) {return x.data_ == y.data_;}
  30. };
  31. #if TEST_STD_VER > 11
  32. struct Final final {};
  33. #endif
  34. int main(int, char**)
  35. {
  36. {
  37. try
  38. {
  39. A a(3);
  40. std::throw_with_nested(a);
  41. assert(false);
  42. }
  43. catch (const A& a)
  44. {
  45. assert(a == A(3));
  46. }
  47. }
  48. {
  49. try
  50. {
  51. A a(4);
  52. std::throw_with_nested(a);
  53. assert(false);
  54. }
  55. catch (const std::nested_exception& e)
  56. {
  57. assert(e.nested_ptr() == nullptr);
  58. }
  59. }
  60. {
  61. try
  62. {
  63. B b(5);
  64. std::throw_with_nested(b);
  65. assert(false);
  66. }
  67. catch (const B& b)
  68. {
  69. assert(b == B(5));
  70. }
  71. }
  72. {
  73. try
  74. {
  75. B b(6);
  76. std::throw_with_nested(b);
  77. assert(false);
  78. }
  79. catch (const std::nested_exception& e)
  80. {
  81. assert(e.nested_ptr() == nullptr);
  82. const B& b = dynamic_cast<const B&>(e);
  83. assert(b == B(6));
  84. }
  85. }
  86. {
  87. try
  88. {
  89. int i = 7;
  90. std::throw_with_nested(i);
  91. assert(false);
  92. }
  93. catch (int i)
  94. {
  95. assert(i == 7);
  96. }
  97. }
  98. {
  99. try
  100. {
  101. std::throw_with_nested("String literal");
  102. assert(false);
  103. }
  104. catch (const char *)
  105. {
  106. }
  107. }
  108. #if TEST_STD_VER > 11
  109. {
  110. try
  111. {
  112. std::throw_with_nested(Final());
  113. assert(false);
  114. }
  115. catch (const Final &)
  116. {
  117. }
  118. }
  119. #endif
  120. return 0;
  121. }