]> git.lizzy.rs Git - rust.git/blob - library/std/src/panic.rs
Rollup merge of #92058 - jsha:run-on-hover, r=GuillaumeGomez
[rust.git] / library / std / src / panic.rs
1 //! Panic support in the standard library.
2
3 #![stable(feature = "std_panic", since = "1.9.0")]
4
5 use crate::any::Any;
6 use crate::collections;
7 use crate::panicking;
8 use crate::sync::{Mutex, RwLock};
9 use crate::thread::Result;
10
11 #[doc(hidden)]
12 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
13 #[allow_internal_unstable(libstd_sys_internals, const_format_args, core_panic)]
14 #[cfg_attr(not(test), rustc_diagnostic_item = "std_panic_2015_macro")]
15 #[rustc_macro_transparency = "semitransparent"]
16 pub macro panic_2015 {
17     () => ({
18         $crate::rt::begin_panic("explicit panic")
19     }),
20     ($msg:expr $(,)?) => ({
21         $crate::rt::begin_panic($msg)
22     }),
23     // Special-case the single-argument case for const_panic.
24     ("{}", $arg:expr $(,)?) => ({
25         $crate::rt::panic_display(&$arg)
26     }),
27     ($fmt:expr, $($arg:tt)+) => ({
28         $crate::rt::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
29     }),
30 }
31
32 #[doc(hidden)]
33 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
34 pub use core::panic::panic_2021;
35
36 #[stable(feature = "panic_hooks", since = "1.10.0")]
37 pub use crate::panicking::{set_hook, take_hook};
38
39 #[stable(feature = "panic_hooks", since = "1.10.0")]
40 pub use core::panic::{Location, PanicInfo};
41
42 #[stable(feature = "catch_unwind", since = "1.9.0")]
43 pub use core::panic::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe};
44
45 /// Panic the current thread with the given message as the panic payload.
46 ///
47 /// The message can be of any (`Any + Send`) type, not just strings.
48 ///
49 /// The message is wrapped in a `Box<'static + Any + Send>`, which can be
50 /// accessed later using [`PanicInfo::payload`].
51 ///
52 /// See the [`panic!`] macro for more information about panicking.
53 #[stable(feature = "panic_any", since = "1.51.0")]
54 #[inline]
55 #[track_caller]
56 pub fn panic_any<M: 'static + Any + Send>(msg: M) -> ! {
57     crate::panicking::begin_panic(msg);
58 }
59
60 #[stable(feature = "catch_unwind", since = "1.9.0")]
61 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
62 #[stable(feature = "catch_unwind", since = "1.9.0")]
63 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
64
65 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
66 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
67 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
68 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
69
70 // https://github.com/rust-lang/rust/issues/62301
71 #[stable(feature = "hashbrown", since = "1.36.0")]
72 impl<K, V, S> UnwindSafe for collections::HashMap<K, V, S>
73 where
74     K: UnwindSafe,
75     V: UnwindSafe,
76     S: UnwindSafe,
77 {
78 }
79
80 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
81 ///
82 /// This function will return `Ok` with the closure's result if the closure
83 /// does not panic, and will return `Err(cause)` if the closure panics. The
84 /// `cause` returned is the object with which panic was originally invoked.
85 ///
86 /// It is currently undefined behavior to unwind from Rust code into foreign
87 /// code, so this function is particularly useful when Rust is called from
88 /// another language (normally C). This can run arbitrary Rust code, capturing a
89 /// panic and allowing a graceful handling of the error.
90 ///
91 /// It is **not** recommended to use this function for a general try/catch
92 /// mechanism. The [`Result`] type is more appropriate to use for functions that
93 /// can fail on a regular basis. Additionally, this function is not guaranteed
94 /// to catch all panics, see the "Notes" section below.
95 ///
96 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
97 /// that all captured variables are safe to cross this boundary. The purpose of
98 /// this bound is to encode the concept of [exception safety][rfc] in the type
99 /// system. Most usage of this function should not need to worry about this
100 /// bound as programs are naturally unwind safe without `unsafe` code. If it
101 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
102 /// assert that the usage here is indeed unwind safe.
103 ///
104 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
105 ///
106 /// # Notes
107 ///
108 /// Note that this function **might not catch all panics** in Rust. A panic in
109 /// Rust is not always implemented via unwinding, but can be implemented by
110 /// aborting the process as well. This function *only* catches unwinding panics,
111 /// not those that abort the process.
112 ///
113 /// Also note that unwinding into Rust code with a foreign exception (e.g.
114 /// an exception thrown from C++ code) is undefined behavior.
115 ///
116 /// # Examples
117 ///
118 /// ```
119 /// use std::panic;
120 ///
121 /// let result = panic::catch_unwind(|| {
122 ///     println!("hello!");
123 /// });
124 /// assert!(result.is_ok());
125 ///
126 /// let result = panic::catch_unwind(|| {
127 ///     panic!("oh no!");
128 /// });
129 /// assert!(result.is_err());
130 /// ```
131 #[stable(feature = "catch_unwind", since = "1.9.0")]
132 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
133     unsafe { panicking::r#try(f) }
134 }
135
136 /// Triggers a panic without invoking the panic hook.
137 ///
138 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
139 /// example, carry a panic across a layer of C code.
140 ///
141 /// # Notes
142 ///
143 /// Note that panics in Rust are not always implemented via unwinding, but they
144 /// may be implemented by aborting the process. If this function is called when
145 /// panics are implemented this way then this function will abort the process,
146 /// not trigger an unwind.
147 ///
148 /// # Examples
149 ///
150 /// ```should_panic
151 /// use std::panic;
152 ///
153 /// let result = panic::catch_unwind(|| {
154 ///     panic!("oh no!");
155 /// });
156 ///
157 /// if let Err(err) = result {
158 ///     panic::resume_unwind(err);
159 /// }
160 /// ```
161 #[stable(feature = "resume_unwind", since = "1.9.0")]
162 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
163     panicking::rust_panic_without_hook(payload)
164 }
165
166 /// Make all future panics abort directly without running the panic hook or unwinding.
167 ///
168 /// There is no way to undo this; the effect lasts until the process exits or
169 /// execs (or the equivalent).
170 ///
171 /// # Use after fork
172 ///
173 /// This function is particularly useful for calling after `libc::fork`.  After `fork`, in a
174 /// multithreaded program it is (on many platforms) not safe to call the allocator.  It is also
175 /// generally highly undesirable for an unwind to unwind past the `fork`, because that results in
176 /// the unwind propagating to code that was only ever expecting to run in the parent.
177 ///
178 /// `panic::always_abort()` helps avoid both of these.  It directly avoids any further unwinding,
179 /// and if there is a panic, the abort will occur without allocating provided that the arguments to
180 /// panic can be formatted without allocating.
181 ///
182 /// Examples
183 ///
184 /// ```no_run
185 /// #![feature(panic_always_abort)]
186 /// use std::panic;
187 ///
188 /// panic::always_abort();
189 ///
190 /// let _ = panic::catch_unwind(|| {
191 ///     panic!("inside the catch");
192 /// });
193 ///
194 /// // We will have aborted already, due to the panic.
195 /// unreachable!();
196 /// ```
197 #[unstable(feature = "panic_always_abort", issue = "84438")]
198 pub fn always_abort() {
199     crate::panicking::panic_count::set_always_abort();
200 }
201
202 #[cfg(test)]
203 mod tests;