Macro pyo3::create_exception
source · macro_rules! create_exception {
($module: ident, $name: ident, $base: ty) => { ... };
($module: ident, $name: ident, $base: ty, $doc: expr) => { ... };
}
Expand description
Defines a new exception type.
Syntax
module
is the name of the containing module.name
is the name of the new exception type.base
is the base class ofMyError
, usuallyPyException
.doc
(optional) is the docstring visible to users (with.__doc__
andhelp()
) and accompanies your error type in your crate’s documentation.
Examples
use pyo3::prelude::*;
use pyo3::create_exception;
use pyo3::exceptions::PyException;
create_exception!(my_module, MyError, PyException, "Some description.");
#[pyfunction]
fn raise_myerror() -> PyResult<()>{
let err = MyError::new_err("Some error happened.");
Err(err)
}
#[pymodule]
fn my_module(py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add("MyError", py.get_type::<MyError>())?;
m.add_function(wrap_pyfunction!(raise_myerror, py)?)?;
Ok(())
}
Python code can handle this exception like any other exception:
from my_module import MyError, raise_myerror
try:
raise_myerror()
except MyError as e:
assert e.__doc__ == 'Some description.'
assert str(e) == 'Some error happened.'