Skip to content

Catching specific exception types via error_already_set #700

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
llchan opened this issue Feb 27, 2017 · 4 comments
Open

Catching specific exception types via error_already_set #700

llchan opened this issue Feb 27, 2017 · 4 comments

Comments

@llchan
Copy link

llchan commented Feb 27, 2017

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;
}
dean0x7d pushed a commit that referenced this issue Apr 2, 2017
This commit adds `error_already_set::matches()` convenience method to
check if the exception trapped by `error_already_set` matches a given
Python exception type. This will address #700 by providing a less
verbose way to check exceptions.
@llchan
Copy link
Author

llchan commented Apr 21, 2017

@romanvm @dean0x7d thanks for adding the helper func. Can we also mention this in the docs?

@dean0x7d
Copy link
Member

@llchan It's mentioned in the API reference for error_already_set.

@llchan
Copy link
Author

llchan commented Apr 22, 2017

I see, looks good, but I was thinking we could also add something in the tutorial-ish section here:
http://pybind11.readthedocs.io/en/master/advanced/exceptions.html

@dean0x7d
Copy link
Member

Ah, right, it does seem like that section is overwhelmingly about C++ -> Python exception translation, but not the other way around. If you have something in mind for it, would you be willing to submit a PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants