File indexing completed on 2025-01-18 10:17:53
0001
0002
0003
0004
0005
0006
0007
0008
0009 #include "test_exceptions.h"
0010
0011 #include "local_bindings.h"
0012 #include "pybind11_tests.h"
0013
0014 #include <exception>
0015 #include <stdexcept>
0016 #include <utility>
0017
0018
0019 class MyException : public std::exception {
0020 public:
0021 explicit MyException(const char *m) : message{m} {}
0022 const char *what() const noexcept override { return message.c_str(); }
0023
0024 private:
0025 std::string message = "";
0026 };
0027
0028
0029 class MyException2 : public std::exception {
0030 public:
0031 explicit MyException2(const char *m) : message{m} {}
0032 const char *what() const noexcept override { return message.c_str(); }
0033
0034 private:
0035 std::string message = "";
0036 };
0037
0038
0039 class MyException3 {
0040 public:
0041 explicit MyException3(const char *m) : message{m} {}
0042 virtual const char *what() const noexcept { return message.c_str(); }
0043
0044 MyException3(const MyException3 &) = default;
0045 MyException3(MyException3 &&) = default;
0046 MyException3 &operator=(const MyException3 &) = default;
0047 MyException3 &operator=(MyException3 &&) = default;
0048 virtual ~MyException3() = default;
0049
0050 private:
0051 std::string message = "";
0052 };
0053
0054
0055
0056 class MyException4 : public std::exception {
0057 public:
0058 explicit MyException4(const char *m) : message{m} {}
0059 const char *what() const noexcept override { return message.c_str(); }
0060
0061 private:
0062 std::string message = "";
0063 };
0064
0065
0066 class MyException5 : public std::logic_error {
0067 public:
0068 explicit MyException5(const std::string &what) : std::logic_error(what) {}
0069 };
0070
0071
0072 class MyException5_1 : public MyException5 {
0073 using MyException5::MyException5;
0074 };
0075
0076
0077 class MyException6 : public std::exception {
0078 public:
0079 explicit MyException6(const char *m) : message{m} {}
0080 const char *what() const noexcept override { return message.c_str(); }
0081
0082 private:
0083 std::string message = "";
0084 };
0085
0086 struct PythonCallInDestructor {
0087 explicit PythonCallInDestructor(const py::dict &d) : d(d) {}
0088 ~PythonCallInDestructor() { d["good"] = true; }
0089
0090 py::dict d;
0091 };
0092
0093 struct PythonAlreadySetInDestructor {
0094 explicit PythonAlreadySetInDestructor(const py::str &s) : s(s) {}
0095 ~PythonAlreadySetInDestructor() {
0096 py::dict foo;
0097 try {
0098
0099 py::object o = foo["bar"];
0100 } catch (py::error_already_set &ex) {
0101 ex.discard_as_unraisable(s);
0102 }
0103 }
0104
0105 py::str s;
0106 };
0107
0108 TEST_SUBMODULE(exceptions, m) {
0109 m.def("throw_std_exception",
0110 []() { throw std::runtime_error("This exception was intentionally thrown."); });
0111
0112
0113 static py::exception<MyException> ex(m, "MyException");
0114 py::register_exception_translator([](std::exception_ptr p) {
0115 try {
0116 if (p) {
0117 std::rethrow_exception(p);
0118 }
0119 } catch (const MyException &e) {
0120
0121 ex(e.what());
0122 }
0123 });
0124
0125
0126
0127
0128 py::register_exception_translator([](std::exception_ptr p) {
0129 try {
0130 if (p) {
0131 std::rethrow_exception(p);
0132 }
0133 } catch (const MyException2 &e) {
0134
0135 PyErr_SetString(PyExc_RuntimeError, e.what());
0136 }
0137 });
0138
0139
0140
0141
0142 py::register_exception_translator([](std::exception_ptr p) {
0143 try {
0144 if (p) {
0145 std::rethrow_exception(p);
0146 }
0147 } catch (const MyException4 &e) {
0148 throw MyException(e.what());
0149 }
0150 });
0151
0152
0153 auto ex5 = py::register_exception<MyException5>(m, "MyException5");
0154
0155 py::register_exception<MyException5_1>(m, "MyException5_1", ex5.ptr());
0156
0157
0158
0159 py::register_local_exception_translator([](std::exception_ptr p) {
0160 try {
0161 if (p) {
0162 std::rethrow_exception(p);
0163 }
0164 } catch (const MyException6 &e) {
0165 PyErr_SetString(PyExc_RuntimeError, e.what());
0166 }
0167 });
0168
0169 m.def("throws1", []() { throw MyException("this error should go to a custom type"); });
0170 m.def("throws2",
0171 []() { throw MyException2("this error should go to a standard Python exception"); });
0172 m.def("throws3", []() { throw MyException3("this error cannot be translated"); });
0173 m.def("throws4", []() { throw MyException4("this error is rethrown"); });
0174 m.def("throws5",
0175 []() { throw MyException5("this is a helper-defined translated exception"); });
0176 m.def("throws5_1", []() { throw MyException5_1("MyException5 subclass"); });
0177 m.def("throws6", []() { throw MyException6("MyException6 only handled in this module"); });
0178 m.def("throws_logic_error", []() {
0179 throw std::logic_error("this error should fall through to the standard handler");
0180 });
0181 m.def("throws_overflow_error", []() { throw std::overflow_error(""); });
0182 m.def("throws_local_error", []() { throw LocalException("never caught"); });
0183 m.def("throws_local_simple_error", []() { throw LocalSimpleException("this mod"); });
0184 m.def("exception_matches", []() {
0185 py::dict foo;
0186 try {
0187
0188 py::object o = foo["bar"];
0189 } catch (py::error_already_set &ex) {
0190 if (!ex.matches(PyExc_KeyError)) {
0191 throw;
0192 }
0193 return true;
0194 }
0195 return false;
0196 });
0197 m.def("exception_matches_base", []() {
0198 py::dict foo;
0199 try {
0200
0201 py::object o = foo["bar"];
0202 } catch (py::error_already_set &ex) {
0203 if (!ex.matches(PyExc_Exception)) {
0204 throw;
0205 }
0206 return true;
0207 }
0208 return false;
0209 });
0210 m.def("modulenotfound_exception_matches_base", []() {
0211 try {
0212
0213 py::module_::import("nonexistent");
0214 } catch (py::error_already_set &ex) {
0215 if (!ex.matches(PyExc_ImportError)) {
0216 throw;
0217 }
0218 return true;
0219 }
0220 return false;
0221 });
0222
0223 m.def("throw_already_set", [](bool err) {
0224 if (err) {
0225 PyErr_SetString(PyExc_ValueError, "foo");
0226 }
0227 try {
0228 throw py::error_already_set();
0229 } catch (const std::runtime_error &e) {
0230 if ((err && e.what() != std::string("ValueError: foo"))
0231 || (!err
0232 && e.what()
0233 != std::string("Internal error: pybind11::error_already_set called "
0234 "while Python error indicator not set."))) {
0235 PyErr_Clear();
0236 throw std::runtime_error("error message mismatch");
0237 }
0238 }
0239 PyErr_Clear();
0240 if (err) {
0241 PyErr_SetString(PyExc_ValueError, "foo");
0242 }
0243 throw py::error_already_set();
0244 });
0245
0246 m.def("python_call_in_destructor", [](const py::dict &d) {
0247 bool retval = false;
0248 try {
0249 PythonCallInDestructor set_dict_in_destructor(d);
0250 PyErr_SetString(PyExc_ValueError, "foo");
0251 throw py::error_already_set();
0252 } catch (const py::error_already_set &) {
0253 retval = true;
0254 }
0255 return retval;
0256 });
0257
0258 m.def("python_alreadyset_in_destructor", [](const py::str &s) {
0259 PythonAlreadySetInDestructor alreadyset_in_destructor(s);
0260 return true;
0261 });
0262
0263
0264 m.def("try_catch",
0265 [m](const py::object &exc_type, const py::function &f, const py::args &args) {
0266 try {
0267 f(*args);
0268 } catch (py::error_already_set &ex) {
0269 if (ex.matches(exc_type)) {
0270 py::print(ex.what());
0271 } else {
0272
0273
0274 throw ex;
0275 }
0276 }
0277 });
0278
0279
0280 m.def("simple_bool_passthrough", [](bool x) { return x; });
0281
0282 m.def("throw_should_be_translated_to_key_error", []() { throw shared_exception(); });
0283
0284 m.def("raise_from", []() {
0285 PyErr_SetString(PyExc_ValueError, "inner");
0286 py::raise_from(PyExc_ValueError, "outer");
0287 throw py::error_already_set();
0288 });
0289
0290 m.def("raise_from_already_set", []() {
0291 try {
0292 PyErr_SetString(PyExc_ValueError, "inner");
0293 throw py::error_already_set();
0294 } catch (py::error_already_set &e) {
0295 py::raise_from(e, PyExc_ValueError, "outer");
0296 throw py::error_already_set();
0297 }
0298 });
0299
0300 m.def("throw_nested_exception", []() {
0301 try {
0302 throw std::runtime_error("Inner Exception");
0303 } catch (const std::runtime_error &) {
0304 std::throw_with_nested(std::runtime_error("Outer Exception"));
0305 }
0306 });
0307
0308 m.def("error_already_set_what", [](const py::object &exc_type, const py::object &exc_value) {
0309 PyErr_SetObject(exc_type.ptr(), exc_value.ptr());
0310 std::string what = py::error_already_set().what();
0311 bool py_err_set_after_what = (PyErr_Occurred() != nullptr);
0312 PyErr_Clear();
0313 return py::make_tuple(std::move(what), py_err_set_after_what);
0314 });
0315
0316 m.def("test_cross_module_interleaved_error_already_set", []() {
0317 auto cm = py::module_::import("cross_module_interleaved_error_already_set");
0318 auto interleaved_error_already_set
0319 = reinterpret_cast<void (*)()>(PyLong_AsVoidPtr(cm.attr("funcaddr").ptr()));
0320 interleaved_error_already_set();
0321 });
0322
0323 m.def("test_error_already_set_double_restore", [](bool dry_run) {
0324 PyErr_SetString(PyExc_ValueError, "Random error.");
0325 py::error_already_set e;
0326 e.restore();
0327 PyErr_Clear();
0328 if (!dry_run) {
0329 e.restore();
0330 }
0331 });
0332
0333
0334 m.def("test_pypy_oserror_normalization", []() {
0335 try {
0336 py::module_::import("io").attr("open")("this_filename_must_not_exist", "r");
0337 } catch (const py::error_already_set &e) {
0338 return py::str(e.what());
0339 }
0340 return py::str("UNEXPECTED");
0341 });
0342 }