Catching specific exception types via error_already_set
Open
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 18k
- Forks
- 2.3k
- Avg merge
- 5d 17h
- Merged PRs (30d)
- 10
Description
If I want to perform the C++ equivalent of this python code:
try:
val = d['key']
except KeyError:
return
I can do it like this, but it's rather verbose:
py::object val;
try {
val = d["key"];
} catch (py::error_already_set& exc) {
exc.restore();
if (PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear();
return;
} else {
throw py::error_already_set();
}
}
Is there a more idiomatic way to do this? If not, could we modify the type hierarchy and/or the error_already_set mechanism to allow for something closer to this?
py::object val;
try {
val = d["key"];
} catch (const py::key_error& exc) {
return;
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue names error_already_set, PyErr_ExceptionMatches, and PyExc_KeyError but no files or tests. Start by tracing the existing exception mechanism and its tests, then define the supported typed-catching behavior and verify that KeyError handling remains distinct from other Python exceptions.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp, python
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100