[][src]Macro pyo3::create_exception

macro_rules! create_exception {
    ($module: ident, $name: ident, $base: ty) => { ... };
}

Defines a new exception type.

Syntax

create_exception!(module, MyError, BaseException)

Example

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

create_exception!(mymodule, CustomError, PyException);

fn main() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let error_type = py.get_type::<CustomError>();
    let ctx = [("CustomError", error_type)].into_py_dict(py);
    let type_description: String = py
        .eval("str(CustomError)", None, Some(&ctx))
        .unwrap()
        .extract()
        .unwrap();
    assert_eq!(type_description, "<class 'mymodule.CustomError'>");
    py.run(
        "assert CustomError('oops').args == ('oops',)",
        None,
        Some(ctx),
    )
    .unwrap();
}