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 /// Note that if a custom panic hook has been set, it will be invoked before
118 /// the panic is caught, before unwinding.
120 /// Also note that unwinding into Rust code with a foreign exception (e.g.
121 /// an exception thrown from C++ code) is undefined behavior.
128 /// let result = panic::catch_unwind(|| {
129 /// println!("hello!");
131 /// assert!(result.is_ok());
133 /// let result = panic::catch_unwind(|| {
134 /// panic!("oh no!");
136 /// assert!(result.is_err());
138 #[stable(feature = "catch_unwind", since = "1.9.0")]
139 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
140 unsafe { panicking::r#try(f) }
143 /// Triggers a panic without invoking the panic hook.
145 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
146 /// example, carry a panic across a layer of C code.
150 /// Note that panics in Rust are not always implemented via unwinding, but they
151 /// may be implemented by aborting the process. If this function is called when
152 /// panics are implemented this way then this function will abort the process,
153 /// not trigger an unwind.
160 /// let result = panic::catch_unwind(|| {
161 /// panic!("oh no!");
164 /// if let Err(err) = result {
165 /// panic::resume_unwind(err);
168 #[stable(feature = "resume_unwind", since = "1.9.0")]
169 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
170 panicking::rust_panic_without_hook(payload)
173 /// Make all future panics abort directly without running the panic hook or unwinding.
175 /// There is no way to undo this; the effect lasts until the process exits or
176 /// execs (or the equivalent).
180 /// This function is particularly useful for calling after `libc::fork`. After `fork`, in a
181 /// multithreaded program it is (on many platforms) not safe to call the allocator. It is also
182 /// generally highly undesirable for an unwind to unwind past the `fork`, because that results in
183 /// the unwind propagating to code that was only ever expecting to run in the parent.
185 /// `panic::always_abort()` helps avoid both of these. It directly avoids any further unwinding,
186 /// and if there is a panic, the abort will occur without allocating provided that the arguments to
187 /// panic can be formatted without allocating.
192 /// #![feature(panic_always_abort)]
195 /// panic::always_abort();
197 /// let _ = panic::catch_unwind(|| {
198 /// panic!("inside the catch");
201 /// // We will have aborted already, due to the panic.
204 #[unstable(feature = "panic_always_abort", issue = "84438")]
205 pub fn always_abort() {
206 crate::panicking::panic_count::set_always_abort();
209 /// The configuration for whether and how the default panic hook will capture
210 /// and display the backtrace.
211 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
212 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
214 pub enum BacktraceStyle {
215 /// Prints a terser backtrace which ideally only contains relevant
218 /// Prints a backtrace with all possible information.
220 /// Disable collecting and displaying backtraces.
224 impl BacktraceStyle {
225 pub(crate) fn full() -> Option<Self> {
226 if cfg!(feature = "backtrace") { Some(BacktraceStyle::Full) } else { None }
229 fn as_usize(self) -> usize {
231 BacktraceStyle::Short => 1,
232 BacktraceStyle::Full => 2,
233 BacktraceStyle::Off => 3,
237 fn from_usize(s: usize) -> Option<Self> {
240 1 => BacktraceStyle::Short,
241 2 => BacktraceStyle::Full,
242 3 => BacktraceStyle::Off,
248 // Tracks whether we should/can capture a backtrace, and how we should display
251 // Internally stores equivalent of an Option<BacktraceStyle>.
252 static SHOULD_CAPTURE: AtomicUsize = AtomicUsize::new(0);
254 /// Configure whether the default panic hook will capture and display a
257 /// The default value for this setting may be set by the `RUST_BACKTRACE`
258 /// environment variable; see the details in [`get_backtrace_style`].
259 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
260 pub fn set_backtrace_style(style: BacktraceStyle) {
261 if !cfg!(feature = "backtrace") {
262 // If the `backtrace` feature of this crate isn't enabled, skip setting.
265 SHOULD_CAPTURE.store(style.as_usize(), Ordering::Release);
268 /// Checks whether the standard library's panic hook will capture and print a
271 /// This function will, if a backtrace style has not been set via
272 /// [`set_backtrace_style`], read the environment variable `RUST_BACKTRACE` to
273 /// determine a default value for the backtrace formatting:
275 /// The first call to `get_backtrace_style` may read the `RUST_BACKTRACE`
276 /// environment variable if `set_backtrace_style` has not been called to
277 /// override the default value. After a call to `set_backtrace_style` or
278 /// `get_backtrace_style`, any changes to `RUST_BACKTRACE` will have no effect.
280 /// `RUST_BACKTRACE` is read according to these rules:
282 /// * `0` for `BacktraceStyle::Off`
283 /// * `full` for `BacktraceStyle::Full`
284 /// * `1` for `BacktraceStyle::Short`
285 /// * Other values are currently `BacktraceStyle::Short`, but this may change in
288 /// Returns `None` if backtraces aren't currently supported.
289 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
290 pub fn get_backtrace_style() -> Option<BacktraceStyle> {
291 if !cfg!(feature = "backtrace") {
292 // If the `backtrace` feature of this crate isn't enabled quickly return
293 // `Unsupported` so this can be constant propagated all over the place
294 // to optimize away callers.
297 if let Some(style) = BacktraceStyle::from_usize(SHOULD_CAPTURE.load(Ordering::Acquire)) {
301 let format = crate::env::var_os("RUST_BACKTRACE")
305 } else if &x == "full" {
308 BacktraceStyle::Short
311 .unwrap_or(if cfg!(target_os = "fuchsia") {
312 // Fuchsia components default to full backtrace.
317 set_backtrace_style(format);