Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 2 include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ class error_already_set : public std::runtime_error {
/// Check if the currently trapped error type matches the given Python exception class (or a
/// subclass thereof). May also be passed a tuple to search for any exception class matches in
/// the given tuple.
bool matches(handle ex) const { return PyErr_GivenExceptionMatches(ex.ptr(), m_type.ptr()); }
bool matches(handle exc) const { return PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()); }

const object& type() const { return m_type; }
const object& value() const { return m_value; }
Expand Down
30 changes: 29 additions & 1 deletion 30 tests/test_exceptions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,38 @@ TEST_SUBMODULE(exceptions, m) {
m.def("throws_logic_error", []() { throw std::logic_error("this error should fall through to the standard handler"); });
m.def("exception_matches", []() {
py::dict foo;
try { foo["bar"]; }
try {
// Assign to a py::object to force read access of nonexistent dict entry
py::object o = foo["bar"];
}
catch (py::error_already_set& ex) {
if (!ex.matches(PyExc_KeyError)) throw;
return true;
}
return false;
});
m.def("exception_matches_base", []() {
py::dict foo;
try {
// Assign to a py::object to force read access of nonexistent dict entry
py::object o = foo["bar"];
}
catch (py::error_already_set &ex) {
if (!ex.matches(PyExc_Exception)) throw;
return true;
}
return false;
});
m.def("modulenotfound_exception_matches_base", []() {
try {
// On Python >= 3.6, this raises a ModuleNotFoundError, a subclass of ImportError
py::module::import("nonexistent");
}
catch (py::error_already_set &ex) {
if (!ex.matches(PyExc_ImportError)) throw;
return true;
}
return false;
});

m.def("throw_already_set", [](bool err) {
Expand Down
4 changes: 3 additions & 1 deletion 4 tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ def test_python_call_in_catch():


def test_exception_matches():
m.exception_matches()
assert m.exception_matches()
assert m.exception_matches_base()
assert m.modulenotfound_exception_matches_base()


def test_custom(msg):
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.