You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

173 lines
5.3 KiB

  1. /*
  2. tests/test_custom-exceptions.cpp -- exception translation
  3. Copyright (c) 2016 Pim Schellart <P.Schellart@princeton.edu>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include "pybind11_tests.h"
  8. // A type that should be raised as an exeption in Python
  9. class MyException : public std::exception {
  10. public:
  11. explicit MyException(const char * m) : message{m} {}
  12. virtual const char * what() const noexcept override {return message.c_str();}
  13. private:
  14. std::string message = "";
  15. };
  16. // A type that should be translated to a standard Python exception
  17. class MyException2 : public std::exception {
  18. public:
  19. explicit MyException2(const char * m) : message{m} {}
  20. virtual const char * what() const noexcept override {return message.c_str();}
  21. private:
  22. std::string message = "";
  23. };
  24. // A type that is not derived from std::exception (and is thus unknown)
  25. class MyException3 {
  26. public:
  27. explicit MyException3(const char * m) : message{m} {}
  28. virtual const char * what() const noexcept {return message.c_str();}
  29. private:
  30. std::string message = "";
  31. };
  32. // A type that should be translated to MyException
  33. // and delegated to its exception translator
  34. class MyException4 : public std::exception {
  35. public:
  36. explicit MyException4(const char * m) : message{m} {}
  37. virtual const char * what() const noexcept override {return message.c_str();}
  38. private:
  39. std::string message = "";
  40. };
  41. // Like the above, but declared via the helper function
  42. class MyException5 : public std::logic_error {
  43. public:
  44. explicit MyException5(const std::string &what) : std::logic_error(what) {}
  45. };
  46. // Inherits from MyException5
  47. class MyException5_1 : public MyException5 {
  48. using MyException5::MyException5;
  49. };
  50. void throws1() {
  51. throw MyException("this error should go to a custom type");
  52. }
  53. void throws2() {
  54. throw MyException2("this error should go to a standard Python exception");
  55. }
  56. void throws3() {
  57. throw MyException3("this error cannot be translated");
  58. }
  59. void throws4() {
  60. throw MyException4("this error is rethrown");
  61. }
  62. void throws5() {
  63. throw MyException5("this is a helper-defined translated exception");
  64. }
  65. void throws5_1() {
  66. throw MyException5_1("MyException5 subclass");
  67. }
  68. void throws_logic_error() {
  69. throw std::logic_error("this error should fall through to the standard handler");
  70. }
  71. struct PythonCallInDestructor {
  72. PythonCallInDestructor(const py::dict &d) : d(d) {}
  73. ~PythonCallInDestructor() { d["good"] = py::cast(true); }
  74. py::dict d;
  75. };
  76. test_initializer custom_exceptions([](py::module &m) {
  77. // make a new custom exception and use it as a translation target
  78. static py::exception<MyException> ex(m, "MyException");
  79. py::register_exception_translator([](std::exception_ptr p) {
  80. try {
  81. if (p) std::rethrow_exception(p);
  82. } catch (const MyException &e) {
  83. // Set MyException as the active python error
  84. ex(e.what());
  85. }
  86. });
  87. // register new translator for MyException2
  88. // no need to store anything here because this type will
  89. // never by visible from Python
  90. py::register_exception_translator([](std::exception_ptr p) {
  91. try {
  92. if (p) std::rethrow_exception(p);
  93. } catch (const MyException2 &e) {
  94. // Translate this exception to a standard RuntimeError
  95. PyErr_SetString(PyExc_RuntimeError, e.what());
  96. }
  97. });
  98. // register new translator for MyException4
  99. // which will catch it and delegate to the previously registered
  100. // translator for MyException by throwing a new exception
  101. py::register_exception_translator([](std::exception_ptr p) {
  102. try {
  103. if (p) std::rethrow_exception(p);
  104. } catch (const MyException4 &e) {
  105. throw MyException(e.what());
  106. }
  107. });
  108. // A simple exception translation:
  109. auto ex5 = py::register_exception<MyException5>(m, "MyException5");
  110. // A slightly more complicated one that declares MyException5_1 as a subclass of MyException5
  111. py::register_exception<MyException5_1>(m, "MyException5_1", ex5.ptr());
  112. m.def("throws1", &throws1);
  113. m.def("throws2", &throws2);
  114. m.def("throws3", &throws3);
  115. m.def("throws4", &throws4);
  116. m.def("throws5", &throws5);
  117. m.def("throws5_1", &throws5_1);
  118. m.def("throws_logic_error", &throws_logic_error);
  119. m.def("throw_already_set", [](bool err) {
  120. if (err)
  121. PyErr_SetString(PyExc_ValueError, "foo");
  122. try {
  123. throw py::error_already_set();
  124. } catch (const std::runtime_error& e) {
  125. if ((err && e.what() != std::string("ValueError: foo")) ||
  126. (!err && e.what() != std::string("Unknown internal error occurred")))
  127. {
  128. PyErr_Clear();
  129. throw std::runtime_error("error message mismatch");
  130. }
  131. }
  132. PyErr_Clear();
  133. if (err)
  134. PyErr_SetString(PyExc_ValueError, "foo");
  135. throw py::error_already_set();
  136. });
  137. m.def("python_call_in_destructor", [](py::dict d) {
  138. try {
  139. PythonCallInDestructor set_dict_in_destructor(d);
  140. PyErr_SetString(PyExc_ValueError, "foo");
  141. throw py::error_already_set();
  142. } catch (const py::error_already_set&) {
  143. return true;
  144. }
  145. return false;
  146. });
  147. });