1 //! Panic support in the standard library.
3 #![stable(feature = "std_panic", since = "1.9.0")]
6 use crate::collections;
8 use crate::sync::atomic::{AtomicUsize, Ordering};
9 use crate::sync::{Mutex, RwLock};
10 use crate::thread::Result;
13 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
14 #[allow_internal_unstable(libstd_sys_internals, const_format_args, core_panic, rt)]
15 #[cfg_attr(not(test), rustc_diagnostic_item = "std_panic_2015_macro")]
16 #[rustc_macro_transparency = "semitransparent"]
17 pub macro panic_2015 {
19 $crate::rt::begin_panic("explicit panic")
21 ($msg:expr $(,)?) => ({
22 $crate::rt::begin_panic($msg)
24 // Special-case the single-argument case for const_panic.
25 ("{}", $arg:expr $(,)?) => ({
26 $crate::rt::panic_display(&$arg)
28 ($fmt:expr, $($arg:tt)+) => ({
29 $crate::rt::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
34 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
35 pub use core::panic::panic_2021;
37 #[stable(feature = "panic_hooks", since = "1.10.0")]
38 pub use crate::panicking::{set_hook, take_hook};
40 #[unstable(feature = "panic_update_hook", issue = "92649")]
41 pub use crate::panicking::update_hook;
43 #[stable(feature = "panic_hooks", since = "1.10.0")]
44 pub use core::panic::{Location, PanicInfo};
46 #[stable(feature = "catch_unwind", since = "1.9.0")]
47 pub use core::panic::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe};
49 /// Panic the current thread with the given message as the panic payload.
51 /// The message can be of any (`Any + Send`) type, not just strings.
53 /// The message is wrapped in a `Box<'static + Any + Send>`, which can be
54 /// accessed later using [`PanicInfo::payload`].
56 /// See the [`panic!`] macro for more information about panicking.
57 #[stable(feature = "panic_any", since = "1.51.0")]
60 pub fn panic_any<M: 'static + Any + Send>(msg: M) -> ! {
61 crate::panicking::begin_panic(msg);
64 #[stable(feature = "catch_unwind", since = "1.9.0")]
65 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
66 #[stable(feature = "catch_unwind", since = "1.9.0")]
67 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
69 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
70 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
71 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
72 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
74 // https://github.com/rust-lang/rust/issues/62301
75 #[stable(feature = "hashbrown", since = "1.36.0")]
76 impl<K, V, S> UnwindSafe for collections::HashMap<K, V, S>
84 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
86 /// This function will return `Ok` with the closure's result if the closure
87 /// does not panic, and will return `Err(cause)` if the closure panics. The
88 /// `cause` returned is the object with which panic was originally invoked.
90 /// It is currently undefined behavior to unwind from Rust code into foreign
91 /// code, so this function is particularly useful when Rust is called from
92 /// another language (normally C). This can run arbitrary Rust code, capturing a
93 /// panic and allowing a graceful handling of the error.
95 /// It is **not** recommended to use this function for a general try/catch
96 /// mechanism. The [`Result`] type is more appropriate to use for functions that
97 /// can fail on a regular basis. Additionally, this function is not guaranteed
98 /// to catch all panics, see the "Notes" section below.
100 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
101 /// that all captured variables are safe to cross this boundary. The purpose of
102 /// this bound is to encode the concept of [exception safety][rfc] in the type
103 /// system. Most usage of this function should not need to worry about this
104 /// bound as programs are naturally unwind safe without `unsafe` code. If it
105 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
106 /// assert that the usage here is indeed unwind safe.
108 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
112 /// Note that this function **might not catch all panics** in Rust. A panic in
113 /// Rust is not always implemented via unwinding, but can be implemented by
114 /// aborting the process as well. This function *only* catches unwinding panics,
115 /// not those that abort the process.
117 /// Also note that unwinding into Rust code with a foreign exception (e.g.
118 /// an exception thrown from C++ code) is undefined behavior.
125 /// let result = panic::catch_unwind(|| {
126 /// println!("hello!");
128 /// assert!(result.is_ok());
130 /// let result = panic::catch_unwind(|| {
131 /// panic!("oh no!");
133 /// assert!(result.is_err());
135 #[stable(feature = "catch_unwind", since = "1.9.0")]
136 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
137 unsafe { panicking::r#try(f) }
140 /// Triggers a panic without invoking the panic hook.
142 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
143 /// example, carry a panic across a layer of C code.
147 /// Note that panics in Rust are not always implemented via unwinding, but they
148 /// may be implemented by aborting the process. If this function is called when
149 /// panics are implemented this way then this function will abort the process,
150 /// not trigger an unwind.
157 /// let result = panic::catch_unwind(|| {
158 /// panic!("oh no!");
161 /// if let Err(err) = result {
162 /// panic::resume_unwind(err);
165 #[stable(feature = "resume_unwind", since = "1.9.0")]
166 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
167 panicking::rust_panic_without_hook(payload)
170 /// Make all future panics abort directly without running the panic hook or unwinding.
172 /// There is no way to undo this; the effect lasts until the process exits or
173 /// execs (or the equivalent).
177 /// This function is particularly useful for calling after `libc::fork`. After `fork`, in a
178 /// multithreaded program it is (on many platforms) not safe to call the allocator. It is also
179 /// generally highly undesirable for an unwind to unwind past the `fork`, because that results in
180 /// the unwind propagating to code that was only ever expecting to run in the parent.
182 /// `panic::always_abort()` helps avoid both of these. It directly avoids any further unwinding,
183 /// and if there is a panic, the abort will occur without allocating provided that the arguments to
184 /// panic can be formatted without allocating.
189 /// #![feature(panic_always_abort)]
192 /// panic::always_abort();
194 /// let _ = panic::catch_unwind(|| {
195 /// panic!("inside the catch");
198 /// // We will have aborted already, due to the panic.
201 #[unstable(feature = "panic_always_abort", issue = "84438")]
202 pub fn always_abort() {
203 crate::panicking::panic_count::set_always_abort();
206 /// The configuration for whether and how the default panic hook will capture
207 /// and display the backtrace.
208 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
209 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
211 pub enum BacktraceStyle {
212 /// Prints a terser backtrace which ideally only contains relevant
215 /// Prints a backtrace with all possible information.
217 /// Disable collecting and displaying backtraces.
221 impl BacktraceStyle {
222 pub(crate) fn full() -> Option<Self> {
223 if cfg!(feature = "backtrace") { Some(BacktraceStyle::Full) } else { None }
226 fn as_usize(self) -> usize {
228 BacktraceStyle::Short => 1,
229 BacktraceStyle::Full => 2,
230 BacktraceStyle::Off => 3,
234 fn from_usize(s: usize) -> Option<Self> {
237 1 => BacktraceStyle::Short,
238 2 => BacktraceStyle::Full,
239 3 => BacktraceStyle::Off,
245 // Tracks whether we should/can capture a backtrace, and how we should display
248 // Internally stores equivalent of an Option<BacktraceStyle>.
249 static SHOULD_CAPTURE: AtomicUsize = AtomicUsize::new(0);
251 /// Configure whether the default panic hook will capture and display a
254 /// The default value for this setting may be set by the `RUST_BACKTRACE`
255 /// environment variable; see the details in [`get_backtrace_style`].
256 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
257 pub fn set_backtrace_style(style: BacktraceStyle) {
258 if !cfg!(feature = "backtrace") {
259 // If the `backtrace` feature of this crate isn't enabled, skip setting.
262 SHOULD_CAPTURE.store(style.as_usize(), Ordering::Release);
265 /// Checks whether the standard library's panic hook will capture and print a
268 /// This function will, if a backtrace style has not been set via
269 /// [`set_backtrace_style`], read the environment variable `RUST_BACKTRACE` to
270 /// determine a default value for the backtrace formatting:
272 /// The first call to `get_backtrace_style` may read the `RUST_BACKTRACE`
273 /// environment variable if `set_backtrace_style` has not been called to
274 /// override the default value. After a call to `set_backtrace_style` or
275 /// `get_backtrace_style`, any changes to `RUST_BACKTRACE` will have no effect.
277 /// `RUST_BACKTRACE` is read according to these rules:
279 /// * `0` for `BacktraceStyle::Off`
280 /// * `full` for `BacktraceStyle::Full`
281 /// * `1` for `BacktraceStyle::Short`
282 /// * Other values are currently `BacktraceStyle::Short`, but this may change in
285 /// Returns `None` if backtraces aren't currently supported.
286 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
287 pub fn get_backtrace_style() -> Option<BacktraceStyle> {
288 if !cfg!(feature = "backtrace") {
289 // If the `backtrace` feature of this crate isn't enabled quickly return
290 // `Unsupported` so this can be constant propagated all over the place
291 // to optimize away callers.
294 if let Some(style) = BacktraceStyle::from_usize(SHOULD_CAPTURE.load(Ordering::Acquire)) {
298 let format = crate::env::var_os("RUST_BACKTRACE")
302 } else if &x == "full" {
305 BacktraceStyle::Short
308 .unwrap_or(if cfg!(target_os = "fuchsia") {
309 // Fuchsia components default to full backtrace.
314 set_backtrace_style(format);