blob: 56cd9bc48f751bc9d75e2c1ac6d846a909af8976 [file] [log] [blame]
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001/*
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02002 tests/test_custom-exceptions.cpp -- exception translation
Pim Schellart5a7d17f2016-06-17 17:35:59 -04003
4 Copyright (c) 2016 Pim Schellart <P.Schellart@princeton.edu>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
Dean Moldovana0c1ccf2016-08-12 13:50:00 +020010#include "pybind11_tests.h"
Pim Schellart5a7d17f2016-06-17 17:35:59 -040011
luz.paz28cb6762018-01-09 12:30:19 -050012// A type that should be raised as an exception in Python
Pim Schellart5a7d17f2016-06-17 17:35:59 -040013class MyException : public std::exception {
14public:
15 explicit MyException(const char * m) : message{m} {}
16 virtual const char * what() const noexcept override {return message.c_str();}
17private:
18 std::string message = "";
19};
20
21// A type that should be translated to a standard Python exception
22class MyException2 : public std::exception {
23public:
24 explicit MyException2(const char * m) : message{m} {}
25 virtual const char * what() const noexcept override {return message.c_str();}
26private:
27 std::string message = "";
28};
29
30// A type that is not derived from std::exception (and is thus unknown)
31class MyException3 {
32public:
33 explicit MyException3(const char * m) : message{m} {}
34 virtual const char * what() const noexcept {return message.c_str();}
35private:
36 std::string message = "";
37};
38
39// A type that should be translated to MyException
40// and delegated to its exception translator
41class MyException4 : public std::exception {
42public:
43 explicit MyException4(const char * m) : message{m} {}
44 virtual const char * what() const noexcept override {return message.c_str();}
45private:
46 std::string message = "";
47};
48
Jason Rhinelanderb3794f12016-09-16 02:04:15 -040049
50// Like the above, but declared via the helper function
51class MyException5 : public std::logic_error {
52public:
53 explicit MyException5(const std::string &what) : std::logic_error(what) {}
54};
55
56// Inherits from MyException5
57class MyException5_1 : public MyException5 {
58 using MyException5::MyException5;
59};
60
Dean Moldovan135ba8d2016-09-10 11:58:02 +020061struct PythonCallInDestructor {
62 PythonCallInDestructor(const py::dict &d) : d(d) {}
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -050063 ~PythonCallInDestructor() { d["good"] = true; }
Dean Moldovan135ba8d2016-09-10 11:58:02 +020064
65 py::dict d;
66};
67
Jason Rhinelanderabcf43d2017-07-23 12:26:17 -040068TEST_SUBMODULE(exceptions, m) {
Dean Moldovan83e328f2017-06-09 00:44:49 +020069 m.def("throw_std_exception", []() {
70 throw std::runtime_error("This exception was intentionally thrown.");
71 });
72
Pim Schellart5a7d17f2016-06-17 17:35:59 -040073 // make a new custom exception and use it as a translation target
74 static py::exception<MyException> ex(m, "MyException");
75 py::register_exception_translator([](std::exception_ptr p) {
76 try {
77 if (p) std::rethrow_exception(p);
78 } catch (const MyException &e) {
Jason Rhinelanderb3794f12016-09-16 02:04:15 -040079 // Set MyException as the active python error
80 ex(e.what());
Pim Schellart5a7d17f2016-06-17 17:35:59 -040081 }
82 });
83
84 // register new translator for MyException2
85 // no need to store anything here because this type will
86 // never by visible from Python
87 py::register_exception_translator([](std::exception_ptr p) {
88 try {
89 if (p) std::rethrow_exception(p);
90 } catch (const MyException2 &e) {
Jason Rhinelanderb3794f12016-09-16 02:04:15 -040091 // Translate this exception to a standard RuntimeError
Pim Schellart5a7d17f2016-06-17 17:35:59 -040092 PyErr_SetString(PyExc_RuntimeError, e.what());
93 }
94 });
95
96 // register new translator for MyException4
97 // which will catch it and delegate to the previously registered
98 // translator for MyException by throwing a new exception
99 py::register_exception_translator([](std::exception_ptr p) {
100 try {
101 if (p) std::rethrow_exception(p);
102 } catch (const MyException4 &e) {
103 throw MyException(e.what());
104 }
105 });
106
Jason Rhinelanderb3794f12016-09-16 02:04:15 -0400107 // A simple exception translation:
108 auto ex5 = py::register_exception<MyException5>(m, "MyException5");
109 // A slightly more complicated one that declares MyException5_1 as a subclass of MyException5
110 py::register_exception<MyException5_1>(m, "MyException5_1", ex5.ptr());
111
Jason Rhinelanderabcf43d2017-07-23 12:26:17 -0400112 m.def("throws1", []() { throw MyException("this error should go to a custom type"); });
113 m.def("throws2", []() { throw MyException2("this error should go to a standard Python exception"); });
114 m.def("throws3", []() { throw MyException3("this error cannot be translated"); });
115 m.def("throws4", []() { throw MyException4("this error is rethrown"); });
116 m.def("throws5", []() { throw MyException5("this is a helper-defined translated exception"); });
117 m.def("throws5_1", []() { throw MyException5_1("MyException5 subclass"); });
118 m.def("throws_logic_error", []() { throw std::logic_error("this error should fall through to the standard handler"); });
Francesco Biscanideb3cb22019-11-14 08:56:58 +0100119 m.def("throws_overflow_error", []() {throw std::overflow_error(""); });
Jason Rhinelanderabcf43d2017-07-23 12:26:17 -0400120 m.def("exception_matches", []() {
121 py::dict foo;
Yannick Jadoul97784da2019-05-12 23:35:49 +0200122 try {
123 // Assign to a py::object to force read access of nonexistent dict entry
124 py::object o = foo["bar"];
125 }
Jason Rhinelanderabcf43d2017-07-23 12:26:17 -0400126 catch (py::error_already_set& ex) {
Jason Rhinelander1682b672017-07-20 23:14:33 -0400127 if (!ex.matches(PyExc_KeyError)) throw;
Yannick Jadoul97784da2019-05-12 23:35:49 +0200128 return true;
Jason Rhinelanderabcf43d2017-07-23 12:26:17 -0400129 }
Yannick Jadoul97784da2019-05-12 23:35:49 +0200130 return false;
131 });
132 m.def("exception_matches_base", []() {
133 py::dict foo;
134 try {
135 // Assign to a py::object to force read access of nonexistent dict entry
136 py::object o = foo["bar"];
137 }
138 catch (py::error_already_set &ex) {
139 if (!ex.matches(PyExc_Exception)) throw;
140 return true;
141 }
142 return false;
143 });
144 m.def("modulenotfound_exception_matches_base", []() {
145 try {
146 // On Python >= 3.6, this raises a ModuleNotFoundError, a subclass of ImportError
147 py::module::import("nonexistent");
148 }
149 catch (py::error_already_set &ex) {
150 if (!ex.matches(PyExc_ImportError)) throw;
151 return true;
152 }
153 return false;
Jason Rhinelanderabcf43d2017-07-23 12:26:17 -0400154 });
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400155
Ivan Smirnov67b54892016-09-07 21:10:16 +0100156 m.def("throw_already_set", [](bool err) {
157 if (err)
158 PyErr_SetString(PyExc_ValueError, "foo");
159 try {
160 throw py::error_already_set();
161 } catch (const std::runtime_error& e) {
162 if ((err && e.what() != std::string("ValueError: foo")) ||
163 (!err && e.what() != std::string("Unknown internal error occurred")))
164 {
165 PyErr_Clear();
166 throw std::runtime_error("error message mismatch");
167 }
168 }
169 PyErr_Clear();
170 if (err)
171 PyErr_SetString(PyExc_ValueError, "foo");
172 throw py::error_already_set();
173 });
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200174
175 m.def("python_call_in_destructor", [](py::dict d) {
176 try {
177 PythonCallInDestructor set_dict_in_destructor(d);
178 PyErr_SetString(PyExc_ValueError, "foo");
179 throw py::error_already_set();
180 } catch (const py::error_already_set&) {
181 return true;
182 }
183 return false;
184 });
Jason Rhinelander1682b672017-07-20 23:14:33 -0400185
186 // test_nested_throws
187 m.def("try_catch", [m](py::object exc_type, py::function f, py::args args) {
188 try { f(*args); }
189 catch (py::error_already_set &ex) {
190 if (ex.matches(exc_type))
191 py::print(ex.what());
192 else
193 throw;
194 }
195 });
196
Jason Rhinelanderabcf43d2017-07-23 12:26:17 -0400197}