throw_with_nested.pass.cpp (2573B)
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 10 // UNSUPPORTED: libcpp-no-exceptions 11 // <exception> 12 13 // class nested_exception; 14 15 // template<class T> void throw_with_nested [[noreturn]] (T&& t); 16 17 #include <exception> 18 #include <cstdlib> 19 #include <cassert> 20 21 #include "test_macros.h" 22 23 class A 24 { 25 int data_; 26 public: 27 explicit A(int data) : data_(data) {} 28 29 friend bool operator==(const A& x, const A& y) {return x.data_ == y.data_;} 30 }; 31 32 class B 33 : public std::nested_exception 34 { 35 int data_; 36 public: 37 explicit B(int data) : data_(data) {} 38 39 friend bool operator==(const B& x, const B& y) {return x.data_ == y.data_;} 40 }; 41 42 #if TEST_STD_VER > 11 43 struct Final final {}; 44 #endif 45 46 int main() 47 { 48 { 49 try 50 { 51 A a(3); 52 std::throw_with_nested(a); 53 assert(false); 54 } 55 catch (const A& a) 56 { 57 assert(a == A(3)); 58 } 59 } 60 { 61 try 62 { 63 A a(4); 64 std::throw_with_nested(a); 65 assert(false); 66 } 67 catch (const std::nested_exception& e) 68 { 69 assert(e.nested_ptr() == nullptr); 70 } 71 } 72 { 73 try 74 { 75 B b(5); 76 std::throw_with_nested(b); 77 assert(false); 78 } 79 catch (const B& b) 80 { 81 assert(b == B(5)); 82 } 83 } 84 { 85 try 86 { 87 B b(6); 88 std::throw_with_nested(b); 89 assert(false); 90 } 91 catch (const std::nested_exception& e) 92 { 93 assert(e.nested_ptr() == nullptr); 94 const B& b = dynamic_cast<const B&>(e); 95 assert(b == B(6)); 96 } 97 } 98 { 99 try 100 { 101 int i = 7; 102 std::throw_with_nested(i); 103 assert(false); 104 } 105 catch (int i) 106 { 107 assert(i == 7); 108 } 109 } 110 { 111 try 112 { 113 std::throw_with_nested("String literal"); 114 assert(false); 115 } 116 catch (const char *) 117 { 118 } 119 } 120 #if TEST_STD_VER > 11 121 { 122 try 123 { 124 std::throw_with_nested(Final()); 125 assert(false); 126 } 127 catch (const Final &) 128 { 129 } 130 } 131 #endif 132 }