# pyo3::PyErr - Rust
Represents a Python exception that was raised.
Keywords: rust, rustlang, rust-lang, PyErr

# Struct pyo3::PyErr [−] [src]

    pub struct PyErr { /* fields omitted */ }

Represents a Python exception that was raised.

## Implementations

### `impl PyErr` [src]

#### `pub fn new<T, A>(args: A) -> PyErr where
T: PyTypeObject,
A: PyErrArguments + Send + Sync + 'static,` [src]

Creates a new PyErr of type `T`.

`value` can be:

- a tuple: the exception instance will be created using Python `T(*tuple)`
- any other value: the exception instance will be created using Python `T(value)`

Note: if `value` is not `Send` or `Sync`, consider using `PyErr::from_instance` instead.

Panics if `T` is not a Python class derived from `BaseException`.

Example:

ⓘ

    return Err(PyErr::new::<exceptions::PyTypeError, _>("Error message"));

In most cases, you can use a concrete exception’s constructor instead, which is equivalent:

ⓘ

    return Err(exceptions::PyTypeError::new_err("Error message"));

#### `pub fn from_type<A>(ty: &PyType, args: A) -> PyErr where
A: PyErrArguments + Send + Sync + 'static,` [src]

Constructs a new error, with the usual lazy initialization of Python exceptions.

`exc` is the exception type; usually one of the standard exceptions like `exceptions::PyRuntimeError`. `args` is the a tuple of arguments to pass to the exception constructor.

#### `pub fn from_instance(obj: &PyAny) -> PyErr` [src]

Creates a new PyErr.

`obj` must be an Python exception instance, the PyErr will use that instance. If `obj` is a Python exception type object, the PyErr will (lazily) create a new instance of that type. Otherwise, a `TypeError` is created instead.

# Example

    use pyo3::{Python, PyErr, IntoPy, exceptions::PyTypeError, types::PyType};
    Python::with_gil(|py| {
        // Case #1: Exception instance
        let err = PyErr::from_instance(PyTypeError::new_err("some type error",).instance(py));
        assert_eq!(err.to_string(), "TypeError: some type error");

        // Case #2: Exception type
        let err = PyErr::from_instance(PyType::new::<PyTypeError>(py));
        assert_eq!(err.to_string(), "TypeError: ");

        // Case #3: Invalid exception value
        let err = PyErr::from_instance("foo".into_py(py).as_ref(py));
        assert_eq!(err.to_string(), "TypeError: exceptions must derive from BaseException");
    });

#### `pub fn ptype<'py>(&'py self, py: Python<'py>) -> &'py PyType` [src]

Get the type of this exception object.

The object will be normalized first if needed.

# Example

    use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
    Python::with_gil(|py| {
        let err = PyTypeError::new_err(("some type error",));
        assert_eq!(err.ptype(py), PyType::new::<PyTypeError>(py));
    });

#### `pub fn pvalue<'py>(&'py self, py: Python<'py>) -> &'py PyBaseException` [src]

Get the value of this exception object.

The object will be normalized first if needed.

# Example

    use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
    Python::with_gil(|py| {
        let err = PyTypeError::new_err(("some type error",));
        assert!(err.is_instance::<PyTypeError>(py));
        assert_eq!(err.pvalue(py).to_string(), "some type error");
    });

#### `pub fn ptraceback<'py>(&'py self, py: Python<'py>) -> Option<&'py PyAny>` [src]

Get the value of this exception object.

The object will be normalized first if needed.

# Example

    use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
    Python::with_gil(|py| {
        let err = PyTypeError::new_err(("some type error",));
        assert_eq!(err.ptraceback(py), None);
    });

#### `pub fn occurred(_: Python<'_>) -> bool` [src]

Gets whether an error is present in the Python interpreter’s global state.

#### `pub fn fetch(py: Python<'_>) -> PyErr` [src]

Retrieves the current error from the Python interpreter’s global state.

The error is cleared from the Python interpreter. If no error is set, returns a `SystemError`.

If the error fetched is a `PanicException` (which would have originated from a panic in a pyo3 callback) then this function will resume the panic.

#### `pub fn new_type<'p>(
_: Python<'p>,
name: &str,
base: Option<&PyType>,
dict: Option<PyObject>
) -> NonNull<PyTypeObject>` [src]

Creates a new exception type with the given name, which must be of the form `<module>.<ExceptionName>`, as required by `PyErr_NewException`.

`base` can be an existing exception type to subclass, or a tuple of classes `dict` specifies an optional dictionary of class variables and methods

#### `pub fn print(&self, py: Python<'_>)` [src]

Prints a standard traceback to `sys.stderr`.

#### `pub fn print_and_set_sys_last_vars(&self, py: Python<'_>)` [src]

Prints a standard traceback to `sys.stderr`, and sets `sys.last_{type,value,traceback}` attributes to this exception’s data.

#### `pub fn matches<T>(&self, py: Python<'_>, exc: T) -> bool where
T: ToBorrowedObject,` [src]

Returns true if the current exception matches the exception in `exc`.

If `exc` is a class object, this also returns `true` when `self` is an instance of a subclass. If `exc` is a tuple, all exceptions in the tuple (and recursively in subtuples) are searched for a match.

#### `pub fn is_instance<T>(&self, py: Python<'_>) -> bool where
T: PyTypeObject,` [src]

Returns true if the current exception is instance of `T`.

#### `pub fn instance<'py>(&'py self, py: Python<'py>) -> &'py PyBaseException` [src]

Retrieves the exception instance for this error.

#### `pub fn into_instance(self, py: Python<'_>) -> Py<PyBaseException>` [src]

Consumes self to take ownership of the exception instance for this error.

#### `pub fn restore(self, py: Python<'_>)` [src]

Writes the error back to the Python interpreter’s global state. This is the opposite of `PyErr::fetch()`.

#### `pub fn warn(
py: Python<'_>,
category: &PyAny,
message: &str,
stacklevel: i32
) -> PyResult<()>` [src]

Issues a warning message. May return a `PyErr` if warnings-as-errors is enabled.

#### `pub fn clone_ref(&self, py: Python<'_>) -> PyErr` [src]

Clone the PyErr. This requires the GIL, which is why PyErr does not implement Clone.

# Example

    use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
    Python::with_gil(|py| {
        let err = PyTypeError::new_err(("some type error",));
        let err_clone = err.clone_ref(py);
        assert_eq!(err.ptype(py), err_clone.ptype(py));
        assert_eq!(err.pvalue(py), err_clone.pvalue(py));
        assert_eq!(err.ptraceback(py), err_clone.ptraceback(py));
    });

## Trait Implementations

### `impl Debug for PyErr` [src]

#### `fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>` [src]

Formats the value using the given formatter. Read more

### `impl Display for PyErr` [src]

#### `fn fmt(&self, f: &mut Formatter<'_>) -> Result` [src]

Formats the value using the given formatter. Read more

### `impl Error for PyErr` [src]

#### `pub fn source(&self) -> Option<&(dyn Error + 'static)>`1.30.0 [src]

The lower-level source of this error, if any. Read more

#### `pub fn backtrace(&self) -> Option<&Backtrace>` [src]

🔬 This is a nightly-only experimental API. (`backtrace`)

Returns a stack backtrace, if available, of where this error occurred. Read more

#### `pub fn description(&self) -> &str` 1.0.0 [src]

👎 Deprecated since 1.42.0:

use the Display impl or to_string()

Read more

#### `pub fn cause(&self) -> Option<&dyn Error>`1.0.0 [src]

👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

### `impl From<&'_ CancelledError> for PyErr` [src]

#### `fn from(err: &CancelledError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ IncompleteReadError> for PyErr` [src]

#### `fn from(err: &IncompleteReadError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ InvalidStateError> for PyErr` [src]

#### `fn from(err: &InvalidStateError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ LimitOverrunError> for PyErr` [src]

#### `fn from(err: &LimitOverrunError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PanicException> for PyErr` [src]

#### `fn from(err: &PanicException) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyArithmeticError> for PyErr` [src]

#### `fn from(err: &PyArithmeticError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyAssertionError> for PyErr` [src]

#### `fn from(err: &PyAssertionError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyAttributeError> for PyErr` [src]

#### `fn from(err: &PyAttributeError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyBaseException> for PyErr` [src]

#### `fn from(err: &PyBaseException) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyBlockingIOError> for PyErr` [src]

#### `fn from(err: &PyBlockingIOError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyBrokenPipeError> for PyErr` [src]

#### `fn from(err: &PyBrokenPipeError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyBufferError> for PyErr` [src]

#### `fn from(err: &PyBufferError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyChildProcessError> for PyErr` [src]

#### `fn from(err: &PyChildProcessError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyConnectionAbortedError> for PyErr` [src]

#### `fn from(err: &PyConnectionAbortedError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyConnectionError> for PyErr` [src]

#### `fn from(err: &PyConnectionError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyConnectionRefusedError> for PyErr` [src]

#### `fn from(err: &PyConnectionRefusedError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyConnectionResetError> for PyErr` [src]

#### `fn from(err: &PyConnectionResetError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyEOFError> for PyErr` [src]

#### `fn from(err: &PyEOFError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyEnvironmentError> for PyErr` [src]

#### `fn from(err: &PyEnvironmentError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyException> for PyErr` [src]

#### `fn from(err: &PyException) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyFileExistsError> for PyErr` [src]

#### `fn from(err: &PyFileExistsError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyFileNotFoundError> for PyErr` [src]

#### `fn from(err: &PyFileNotFoundError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyFloatingPointError> for PyErr` [src]

#### `fn from(err: &PyFloatingPointError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyGeneratorExit> for PyErr` [src]

#### `fn from(err: &PyGeneratorExit) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyIOError> for PyErr` [src]

#### `fn from(err: &PyIOError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyImportError> for PyErr` [src]

#### `fn from(err: &PyImportError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyIndexError> for PyErr` [src]

#### `fn from(err: &PyIndexError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyInterruptedError> for PyErr` [src]

#### `fn from(err: &PyInterruptedError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyIsADirectoryError> for PyErr` [src]

#### `fn from(err: &PyIsADirectoryError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyKeyError> for PyErr` [src]

#### `fn from(err: &PyKeyError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyKeyboardInterrupt> for PyErr` [src]

#### `fn from(err: &PyKeyboardInterrupt) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyLookupError> for PyErr` [src]

#### `fn from(err: &PyLookupError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyMemoryError> for PyErr` [src]

#### `fn from(err: &PyMemoryError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyModuleNotFoundError> for PyErr` [src]

#### `fn from(err: &PyModuleNotFoundError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyNameError> for PyErr` [src]

#### `fn from(err: &PyNameError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyNotADirectoryError> for PyErr` [src]

#### `fn from(err: &PyNotADirectoryError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyNotImplementedError> for PyErr` [src]

#### `fn from(err: &PyNotImplementedError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyOSError> for PyErr` [src]

#### `fn from(err: &PyOSError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyOverflowError> for PyErr` [src]

#### `fn from(err: &PyOverflowError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyPermissionError> for PyErr` [src]

#### `fn from(err: &PyPermissionError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyProcessLookupError> for PyErr` [src]

#### `fn from(err: &PyProcessLookupError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyRecursionError> for PyErr` [src]

#### `fn from(err: &PyRecursionError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyReferenceError> for PyErr` [src]

#### `fn from(err: &PyReferenceError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyRuntimeError> for PyErr` [src]

#### `fn from(err: &PyRuntimeError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyStopAsyncIteration> for PyErr` [src]

#### `fn from(err: &PyStopAsyncIteration) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyStopIteration> for PyErr` [src]

#### `fn from(err: &PyStopIteration) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PySyntaxError> for PyErr` [src]

#### `fn from(err: &PySyntaxError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PySystemError> for PyErr` [src]

#### `fn from(err: &PySystemError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PySystemExit> for PyErr` [src]

#### `fn from(err: &PySystemExit) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyTimeoutError> for PyErr` [src]

#### `fn from(err: &PyTimeoutError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyTypeError> for PyErr` [src]

#### `fn from(err: &PyTypeError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyUnboundLocalError> for PyErr` [src]

#### `fn from(err: &PyUnboundLocalError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyUnicodeDecodeError> for PyErr` [src]

#### `fn from(err: &PyUnicodeDecodeError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyUnicodeEncodeError> for PyErr` [src]

#### `fn from(err: &PyUnicodeEncodeError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyUnicodeError> for PyErr` [src]

#### `fn from(err: &PyUnicodeError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyUnicodeTranslateError> for PyErr` [src]

#### `fn from(err: &PyUnicodeTranslateError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyValueError> for PyErr` [src]

#### `fn from(err: &PyValueError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ PyZeroDivisionError> for PyErr` [src]

#### `fn from(err: &PyZeroDivisionError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ QueueEmpty> for PyErr` [src]

#### `fn from(err: &QueueEmpty) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ QueueFull> for PyErr` [src]

#### `fn from(err: &QueueFull) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ TimeoutError> for PyErr` [src]

#### `fn from(err: &TimeoutError) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ gaierror> for PyErr` [src]

#### `fn from(err: &gaierror) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ herror> for PyErr` [src]

#### `fn from(err: &herror) -> PyErr` [src]

Performs the conversion.

### `impl From<&'_ timeout> for PyErr` [src]

#### `fn from(err: &timeout) -> PyErr` [src]

Performs the conversion.

### `impl From<AddrParseError> for PyErr` [src]

#### `fn from(err: AddrParseError) -> PyErr` [src]

Performs the conversion.

### `impl From<DecodeUtf16Error> for PyErr` [src]

#### `fn from(err: DecodeUtf16Error) -> PyErr` [src]

Performs the conversion.

### `impl From<Error> for PyErr` [src]

Create `OSError` from `io::Error`

#### `fn from(err: Error) -> PyErr` [src]

Performs the conversion.

### `impl From<FromUtf16Error> for PyErr` [src]

#### `fn from(err: FromUtf16Error) -> PyErr` [src]

Performs the conversion.

### `impl From<FromUtf8Error> for PyErr` [src]

#### `fn from(err: FromUtf8Error) -> PyErr` [src]

Performs the conversion.

### `impl From<Infallible> for PyErr` [src]

#### `fn from(_: Infallible) -> PyErr` [src]

Performs the conversion.

### `impl<W: 'static + Send + Sync + Debug> From<IntoInnerError<W>> for PyErr` [src]

#### `fn from(err: IntoInnerError<W>) -> PyErr` [src]

Performs the conversion.

### `impl From<IntoStringError> for PyErr` [src]

#### `fn from(err: IntoStringError) -> PyErr` [src]

Performs the conversion.

### `impl From<NulError> for PyErr` [src]

#### `fn from(err: NulError) -> PyErr` [src]

Performs the conversion.

### `impl From<ParseBoolError> for PyErr` [src]

#### `fn from(err: ParseBoolError) -> PyErr` [src]

Performs the conversion.

### `impl From<ParseFloatError> for PyErr` [src]

#### `fn from(err: ParseFloatError) -> PyErr` [src]

Performs the conversion.

### `impl From<ParseIntError> for PyErr` [src]

#### `fn from(err: ParseIntError) -> PyErr` [src]

Performs the conversion.

### `impl From<PyBorrowError> for PyErr` [src]

#### `fn from(other: PyBorrowError) -> Self` [src]

Performs the conversion.

### `impl From<PyBorrowMutError> for PyErr` [src]

#### `fn from(other: PyBorrowMutError) -> Self` [src]

Performs the conversion.

### `impl<'a> From<PyDowncastError<'a>> for PyErr` [src]

Convert `PyDowncastError` to Python `TypeError`.

#### `fn from(err: PyDowncastError<'_>) -> PyErr` [src]

Performs the conversion.

### `impl From<PyErr> for Error` [src]

Convert `PyErr` to `io::Error`

#### `fn from(err: PyErr) -> Self` [src]

Performs the conversion.

### `impl From<TryFromIntError> for PyErr` [src]

#### `fn from(err: TryFromIntError) -> PyErr` [src]

Performs the conversion.

### `impl From<TryFromSliceError> for PyErr` [src]

#### `fn from(err: TryFromSliceError) -> PyErr` [src]

Performs the conversion.

### `impl From<Utf8Error> for PyErr` [src]

#### `fn from(err: Utf8Error) -> PyErr` [src]

Performs the conversion.

### `impl IntoPy<Py<PyAny>> for PyErr` [src]

#### `fn into_py(self, py: Python<'_>) -> PyObject` [src]

Performs the conversion.

### `impl<'a> IntoPy<Py<PyAny>> for &'a PyErr` [src]

#### `fn into_py(self, py: Python<'_>) -> PyObject` [src]

Performs the conversion.

### `impl Send for PyErr` [src]

### `impl Sync for PyErr` [src]

### `impl ToPyObject for PyErr` [src]

#### `fn to_object(&self, py: Python<'_>) -> PyObject` [src]

Converts self into a Python object.

## Auto Trait Implementations

### `impl !RefUnwindSafe for PyErr`

### `impl Unpin for PyErr`

### `impl !UnwindSafe for PyErr`

## Blanket Implementations

### `impl<T> Any for T where
T: 'static + ?Sized,` [src]

#### `pub fn type_id(&self) -> TypeId` [src]

Gets the `TypeId` of `self`. Read more

### `impl<T> Borrow<T> for T where
T: ?Sized,` [src]

#### `pub fn borrow(&self) -> &T` [src]

Immutably borrows from an owned value. Read more

### `impl<T> BorrowMut<T> for T where
T: ?Sized,` [src]

#### `pub fn borrow_mut(&mut self) -> &mut T` [src]

Mutably borrows from an owned value. Read more

### `impl<T> From<T> for T` [src]

#### `pub fn from(t: T) -> T` [src]

Performs the conversion.

### `impl<T, U> Into<U> for T where
U: From<T>,` [src]

#### `pub fn into(self) -> U` [src]

Performs the conversion.

### `impl<T> ToBorrowedObject for T where
T: ToPyObject,` [src]

#### `fn with_borrowed_ptr<F, R>(&self, py: Python<'_>, f: F) -> R where
F: FnOnce(*mut PyObject) -> R,` [src]

Converts self into a Python object and calls the specified closure on the native FFI pointer underlying the Python object. Read more

### `impl<T> ToString for T where
T: Display + ?Sized,` [src]

#### `pub default fn to_string(&self) -> String` [src]

Converts the given value to a `String`. Read more

### `impl<T, U> TryFrom<U> for T where
U: Into<T>,` [src]

#### `type Error = Infallible`

The type returned in the event of a conversion error.

#### `pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>` [src]

Performs the conversion.

### `impl<T, U> TryInto<U> for T where
U: TryFrom<T>,` [src]

#### `type Error = <U as TryFrom<T>>::Error`

The type returned in the event of a conversion error.

#### `pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>` [src]

Performs the conversion.