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