MCPcopy Create free account
hub / github.com/pybind/pybind11 / TEST_SUBMODULE

Function TEST_SUBMODULE

tests/test_exceptions.cpp:124–427  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

122};
123
124TEST_SUBMODULE(exceptions, m) {
125 m.def("throw_std_exception",
126 []() { throw std::runtime_error("This exception was intentionally thrown."); });
127
128 // PLEASE KEEP IN SYNC with docs/advanced/exceptions.rst
129 PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> ex_storage;
130 ex_storage.call_once_and_store_result(
131 [&]() { return py::exception<MyException>(m, "MyException"); });
132 py::register_exception_translator([](std::exception_ptr p) {
133 try {
134 if (p) {
135 std::rethrow_exception(p);
136 }
137 } catch (const MyException &e) {
138 // Set MyException as the active python error
139 py::set_error(ex_storage.get_stored(), e.what());
140 }
141 });
142
143 // Same as above, but using the deprecated `py::exception<>::operator()`
144 // We want to be sure it still works, until it's removed.
145 static const auto *const exd = new py::exception<MyExceptionUseDeprecatedOperatorCall>(
146 m, "MyExceptionUseDeprecatedOperatorCall");
147 py::register_exception_translator([](std::exception_ptr p) {
148 try {
149 if (p) {
150 std::rethrow_exception(p);
151 }
152 } catch (const MyExceptionUseDeprecatedOperatorCall &e) {
153#if defined(__INTEL_COMPILER) || defined(__NVCOMPILER)
154 // It is not worth the trouble dealing with warning suppressions for these compilers.
155 // Falling back to the recommended approach to keep the test code simple.
156 py::set_error(*exd, e.what());
157#else
158 PYBIND11_WARNING_PUSH
159 PYBIND11_WARNING_DISABLE_CLANG("-Wdeprecated-declarations")
160 PYBIND11_WARNING_DISABLE_GCC("-Wdeprecated-declarations")
161 PYBIND11_WARNING_DISABLE_MSVC(4996)
162 (*exd)(e.what());
163 PYBIND11_WARNING_POP
164#endif
165 }
166 });
167
168 // register new translator for MyException2
169 // no need to store anything here because this type will
170 // never by visible from Python
171 py::register_exception_translator([](std::exception_ptr p) {
172 try {
173 if (p) {
174 std::rethrow_exception(p);
175 }
176 } catch (const MyException2 &e) {
177 // Translate this exception to a standard RuntimeError
178 py::set_error(PyExc_RuntimeError, e.what());
179 }
180 });
181

Callers

nothing calls this directly

Calls 15

MyExceptionClass · 0.85
MyException2Class · 0.85
MyException3Class · 0.85
MyException4Class · 0.85
MyException5Class · 0.85
MyException5_1Class · 0.85
MyException6Class · 0.85
LocalExceptionClass · 0.85

Tested by

no test coverage detected