Skip to content

Catching specific exception types via error_already_set #700

@llchan

Description

@llchan

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions