pub struct PyException(/* private fields */);
Expand description
Represents Python’s Exception
exception.
§Example: Raising Exception from Rust
This exception can be sent to Python code by converting it into a
PyErr
, where Python code can then catch it.
use pyo3::prelude::*;
use pyo3::exceptions::PyException;
#[pyfunction]
fn always_throws() -> PyResult<()> {
let message = "I'm Exception, and I was raised from Rust.";
Err(PyException::new_err(message))
}
Python code:
from my_module import always_throws
try:
always_throws()
except Exception as e:
print(f"Caught an exception: {e}")
§Example: Catching Exception in Rust
use pyo3::prelude::*;
use pyo3::exceptions::PyException;
Python::with_gil(|py| {
let result: PyResult<()> = py.run_bound("raise Exception", None, None);
let error_type = match result {
Ok(_) => "Not an error",
Err(error) if error.is_instance_of::<PyException>(py) => "Exception",
Err(_) => "Some other error",
};
assert_eq!(error_type, "Exception");
});
Implementations§
Source§impl PyException
impl PyException
Trait Implementations§
Source§impl AsPyPointer for PyException
impl AsPyPointer for PyException
Source§impl AsRef<PyAny> for PyException
impl AsRef<PyAny> for PyException
Source§impl Deref for PyException
impl Deref for PyException
Source§impl PyTypeInfo for PyException
impl PyTypeInfo for PyException
Source§fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject
fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject
Returns the PyTypeObject instance for this type.
Source§fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType>
fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType>
Returns the safe abstraction over the type object.
impl DerefToPyAny for PyException
impl PyLayout<PyException> for PyBaseExceptionObject
impl PySizedLayout<PyException> for PyBaseExceptionObject
impl ToPyErr for PyException
Auto Trait Implementations§
impl !Freeze for PyException
impl !RefUnwindSafe for PyException
impl !Send for PyException
impl !Sync for PyException
impl Unpin for PyException
impl UnwindSafe for PyException
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more