Skip to main content

pyo3/
panic.rs

1//! Helper to convert Rust panics to Python exceptions.
2use crate::exceptions::PyBaseException;
3use crate::platform::prelude::*;
4use crate::PyErr;
5use core::any::Any;
6
7pyo3_exception!(
8    "
9The exception raised when Rust code called from Python panics.
10
11Like SystemExit, this exception is derived from BaseException so that
12it will typically propagate all the way through the stack and cause the
13Python interpreter to exit.
14",
15    PanicException,
16    PyBaseException
17);
18
19impl PanicException {
20    /// Creates a new PanicException from a panic payload.
21    ///
22    /// Attempts to format the error in the same way panic does.
23    #[cold]
24    pub(crate) fn from_panic_payload(payload: Box<dyn Any + Send + 'static>) -> PyErr {
25        if let Some(string) = payload.downcast_ref::<String>() {
26            Self::new_err((string.clone(),))
27        } else if let Some(s) = payload.downcast_ref::<&str>() {
28            Self::new_err((s.to_string(),))
29        } else {
30            Self::new_err(("panic from Rust code",))
31        }
32    }
33}