guide: show exporting create_exception! exceptions in a module
This commit is contained in:
parent
bcb90775b4
commit
4467cf51db
|
@ -33,6 +33,23 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
When using PyO3 to create an extension module, you can add the new exception to
|
||||
the module like this, so that it is importable from Python:
|
||||
|
||||
```rust,ignore
|
||||
|
||||
create_exception!(mymodule, CustomError, PyException);
|
||||
|
||||
#[pymodule]
|
||||
fn mymodule(py: Python, m: &PyModule) -> PyResult<()> {
|
||||
// ... other elements added to module ...
|
||||
m.add("CustomError", py.get_type::<CustomError>())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Raising an exception
|
||||
|
||||
To raise an exception, first you need to obtain an exception type and construct a new [`PyErr`], then call the [`PyErr::restore`](https://docs.rs/pyo3/latest/pyo3/struct.PyErr.html#method.restore) method to write the exception back to the Python interpreter's global state.
|
||||
|
|
Loading…
Reference in a new issue