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.


  • 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.


use pyo3::prelude::*;
use pyo3::create_exception;
use pyo3::exceptions::PyException;

create_exception!(my_module, MyError, PyException, "Some description.");

fn raise_myerror() -> PyResult<()> {
    let err = MyError::new_err("Some error happened.");

fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(raise_myerror, m)?)?;

Python code can handle this exception like any other exception:

from my_module import MyError, raise_myerror

except MyError as e:
    assert e.__doc__ == 'Some description.'
    assert str(e) == 'Some error happened.'