Skip to content

Commit

Permalink
Add support for nested exceptions in custom exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
cbalioglu committed Nov 28, 2022
1 parent 06003e8 commit 6b9f653
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
6 changes: 5 additions & 1 deletion include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -2535,7 +2535,9 @@ class exception : public object {
}

// Sets the current python exception to this exception object with the given message
void operator()(const char *message) { PyErr_SetString(m_ptr, message); }
void operator()(const char *message) {
detail::raise_err(m_ptr, message);
}
};

PYBIND11_NAMESPACE_BEGIN(detail)
Expand Down Expand Up @@ -2567,6 +2569,8 @@ register_exception_impl(handle scope, const char *name, handle base, bool isLoca
try {
std::rethrow_exception(p);
} catch (const CppException &e) {
detail::handle_nested_exception(e, p);

detail::get_exception_object<CppException>()(e.what());
}
});
Expand Down
8 changes: 8 additions & 0 deletions tests/test_exceptions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,14 @@ TEST_SUBMODULE(exceptions, m) {
}
});

m.def("throw_custom_nested_exception", []() {
try {
throw std::runtime_error("Inner Exception");
} catch (const std::runtime_error &) {
std::throw_with_nested(MyException5("Outer Exception"));
}
});

m.def("error_already_set_what", [](const py::object &exc_type, const py::object &exc_value) {
PyErr_SetObject(exc_type.ptr(), exc_value.ptr());
std::string what = py::error_already_set().what();
Expand Down
7 changes: 7 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,13 @@ def test_throw_nested_exception():
assert str(excinfo.value.__cause__) == "Inner Exception"


def test_throw_custom_nested_exception():
with pytest.raises(m.MyException5) as excinfo:
m.throw_custom_nested_exception()
assert str(excinfo.value) == "Outer Exception"
assert str(excinfo.value.__cause__) == "Inner Exception"


# This can often happen if you wrap a pybind11 class in a Python wrapper
def test_invalid_repr():
class MyRepr:
Expand Down

0 comments on commit 6b9f653

Please sign in to comment.