Skip to content
Merged
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
47 changes: 47 additions & 0 deletions guide/src/exception.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,50 @@ defines exceptions for several standard library modules.
[`PyErr::from_value`]: {{#PYO3_DOCS_URL}}/pyo3/struct.PyErr.html#method.from_value
[`PyAny::is_instance`]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.is_instance
[`PyAny::is_instance_of`]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.is_instance_of

## Creating more complex exceptions

If you need to create an exception with more complex behavior, you can also manually create a subclass of `PyException`:

```rust
#![allow(dead_code)]
# #[cfg(any(not(feature = "abi3")))] {
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
use pyo3::exceptions::PyException;

#[pyclass(extends=PyException)]
struct CustomError {
#[pyo3(get)]
url: String,

#[pyo3(get)]
message: String,
}

#[pymethods]
impl CustomError {
#[new]
fn new(url: String, message: String) -> Self {
Self { url, message }
}
}

# fn main() -> PyResult<()> {
Python::with_gil(|py| {
let ctx = [("CustomError", py.get_type::<CustomError>())].into_py_dict(py)?;
pyo3::py_run!(
py,
*ctx,
"assert str(CustomError) == \"<class 'builtins.CustomError'>\", repr(CustomError)"
);
pyo3::py_run!(py, *ctx, "assert CustomError('https://example.com', 'something went bad').args == ('https://example.com', 'something went bad')");
pyo3::py_run!(py, *ctx, "assert CustomError('https://example.com', 'something went bad').url == 'https://example.com'");
# Ok(())
})
# }
# }

```

Note that this is not possible when the ``abi3`` feature is enabled, as that prevents subclassing ``PyException``.
Loading