pyo3

Macro create_exception

Source
macro_rules! create_exception {
    ($module: expr, $name: ident, $base: ty) => { ... };
    ($module: expr, $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 of MyError, usually PyException.
  • doc (optional) is the docstring visible to users (with .__doc__ and help()) 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(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add("MyError", m.py().get_type::<MyError>())?;
    m.add_function(wrap_pyfunction!(raise_myerror, m)?)?;
    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.'