1
0

error.cpp 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "test.h"
  2. TEST_F(PYBIND11_TEST, exception_python_to_cpp) {
  3. auto test = [](const char* code, py_Type type) {
  4. try {
  5. py::exec(code);
  6. } catch(py::python_error& e) {
  7. EXPECT_TRUE(e.match(type));
  8. }
  9. };
  10. test("raise ValueError()", tp_ValueError);
  11. test("raise KeyError()", tp_KeyError);
  12. test("raise IndexError()", tp_IndexError);
  13. test("raise StopIteration()", tp_StopIteration);
  14. test("raise Exception()", tp_Exception);
  15. }
  16. TEST_F(PYBIND11_TEST, exception_cpp_to_python) {
  17. auto m = py::module::__main__();
  18. #define TEST_EXCEPTION(cppe, pye) \
  19. m.def("test_" #cppe, []() { \
  20. throw cppe(#cppe); \
  21. }); \
  22. py::exec("try:\n test_" #cppe "()\nexcept Exception as e:\n assert isinstance(e, " #pye \
  23. ")\n assert str(e) == '" #cppe "'")
  24. using namespace std;
  25. TEST_EXCEPTION(runtime_error, RuntimeError);
  26. TEST_EXCEPTION(domain_error, ValueError);
  27. TEST_EXCEPTION(invalid_argument, ValueError);
  28. TEST_EXCEPTION(length_error, ValueError);
  29. TEST_EXCEPTION(out_of_range, IndexError);
  30. TEST_EXCEPTION(range_error, ValueError);
  31. using namespace py;
  32. m.def("test_stop_iteration", []() {
  33. throw py::stop_iteration();
  34. });
  35. py::exec("try:\n test_stop_iteration()\nexcept StopIteration as e:\n pass");
  36. m.def("test_stop_iteration_value", []() {
  37. throw py::stop_iteration(py::int_(42));
  38. });
  39. py::exec(
  40. "try:\n test_stop_iteration_value()\nexcept StopIteration as e:\n assert e.value == 42");
  41. m.def("test_error_already_set", []() {
  42. KeyError(none().ptr());
  43. throw py::error_already_set();
  44. });
  45. py::exec("try:\n test_error_already_set()\nexcept KeyError as e:\n pass");
  46. m.def("test_error_already_set_matches", []() {
  47. try {
  48. KeyError(none().ptr());
  49. throw py::error_already_set();
  50. } catch(py::error_already_set& e) {
  51. if(e.match(tp_KeyError)) { return; }
  52. std::rethrow_exception(std::current_exception());
  53. }
  54. try {
  55. StopIteration();
  56. throw py::error_already_set();
  57. } catch(py::error_already_set& e) {
  58. if(e.match(type(tp_StopIteration))) { return; }
  59. std::rethrow_exception(std::current_exception());
  60. }
  61. });
  62. py::exec("test_error_already_set_matches()");
  63. TEST_EXCEPTION(index_error, IndexError);
  64. // FIXME: TEST_EXCEPTION(key_error, KeyError);
  65. TEST_EXCEPTION(value_error, ValueError);
  66. TEST_EXCEPTION(type_error, TypeError);
  67. TEST_EXCEPTION(import_error, ImportError);
  68. TEST_EXCEPTION(attribute_error, AttributeError);
  69. TEST_EXCEPTION(runtime_error, RuntimeError);
  70. }