1 //! Panic support in the standard library.
3 #![stable(feature = "core_panic_info", since = "1.41.0")]
8 /// A struct providing information about a panic.
10 /// `PanicInfo` structure is passed to a panic hook set by the [`set_hook`]
13 /// [`set_hook`]: ../../std/panic/fn.set_hook.html
20 /// panic::set_hook(Box::new(|panic_info| {
21 /// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
22 /// println!("panic occurred: {:?}", s);
24 /// println!("panic occurred");
28 /// panic!("Normal panic");
30 #[lang = "panic_info"]
31 #[stable(feature = "panic_hooks", since = "1.10.0")]
33 pub struct PanicInfo<'a> {
34 payload: &'a (dyn Any + Send),
35 message: Option<&'a fmt::Arguments<'a>>,
36 location: &'a Location<'a>,
39 impl<'a> PanicInfo<'a> {
41 feature = "panic_internals",
42 reason = "internal details of the implementation of the `panic!` \
48 pub fn internal_constructor(
49 message: Option<&'a fmt::Arguments<'a>>,
50 location: &'a Location<'a>,
53 PanicInfo { location, message, payload: &NoPayload }
57 feature = "panic_internals",
58 reason = "internal details of the implementation of the `panic!` \
64 pub fn set_payload(&mut self, info: &'a (dyn Any + Send)) {
68 /// Returns the payload associated with the panic.
70 /// This will commonly, but not always, be a `&'static str` or [`String`].
72 /// [`String`]: ../../std/string/struct.String.html
79 /// panic::set_hook(Box::new(|panic_info| {
80 /// println!("panic occurred: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
83 /// panic!("Normal panic");
85 #[stable(feature = "panic_hooks", since = "1.10.0")]
86 pub fn payload(&self) -> &(dyn Any + Send) {
90 /// If the `panic!` macro from the `core` crate (not from `std`)
91 /// was used with a formatting string and some additional arguments,
92 /// returns that message ready to be used for example with [`fmt::write`]
94 /// [`fmt::write`]: ../fmt/fn.write.html
95 #[unstable(feature = "panic_info_message", issue = "66745")]
96 pub fn message(&self) -> Option<&fmt::Arguments<'_>> {
100 /// Returns information about the location from which the panic originated,
103 /// This method will currently always return [`Some`], but this may change
104 /// in future versions.
106 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
113 /// panic::set_hook(Box::new(|panic_info| {
114 /// if let Some(location) = panic_info.location() {
115 /// println!("panic occurred in file '{}' at line {}", location.file(),
116 /// location.line());
118 /// println!("panic occurred but can't get location information...");
122 /// panic!("Normal panic");
124 #[stable(feature = "panic_hooks", since = "1.10.0")]
125 pub fn location(&self) -> Option<&Location<'_>> {
126 // NOTE: If this is changed to sometimes return None,
127 // deal with that case in std::panicking::default_hook and std::panicking::begin_panic_fmt.
132 #[stable(feature = "panic_hook_display", since = "1.26.0")]
133 impl fmt::Display for PanicInfo<'_> {
134 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
135 formatter.write_str("panicked at ")?;
136 if let Some(message) = self.message {
137 write!(formatter, "'{}', ", message)?
138 } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
139 write!(formatter, "'{}', ", payload)?
141 // NOTE: we cannot use downcast_ref::<String>() here
142 // since String is not available in libcore!
143 // The payload is a String when `std::panic!` is called with multiple arguments,
144 // but in that case the message is also available.
146 self.location.fmt(formatter)
150 /// A struct containing information about the location of a panic.
152 /// This structure is created by the [`location`] method of [`PanicInfo`].
154 /// [`location`]: ../../std/panic/struct.PanicInfo.html#method.location
155 /// [`PanicInfo`]: ../../std/panic/struct.PanicInfo.html
162 /// panic::set_hook(Box::new(|panic_info| {
163 /// if let Some(location) = panic_info.location() {
164 /// println!("panic occurred in file '{}' at line {}", location.file(), location.line());
166 /// println!("panic occurred but can't get location information...");
170 /// panic!("Normal panic");
172 #[lang = "panic_location"]
174 #[stable(feature = "panic_hooks", since = "1.10.0")]
175 pub struct Location<'a> {
181 impl<'a> Location<'a> {
182 /// Returns the source location of the caller of this function. If that function's caller is
183 /// annotated then its call location will be returned, and so on up the stack to the first call
184 /// within a non-tracked function body.
189 /// #![feature(track_caller)]
190 /// use core::panic::Location;
192 /// /// Returns the [`Location`] at which it is called.
194 /// fn get_caller_location() -> &'static Location<'static> {
195 /// Location::caller()
198 /// /// Returns a [`Location`] from within this function's definition.
199 /// fn get_just_one_location() -> &'static Location<'static> {
200 /// get_caller_location()
203 /// let fixed_location = get_just_one_location();
204 /// assert_eq!(fixed_location.file(), file!());
205 /// assert_eq!(fixed_location.line(), 15);
206 /// assert_eq!(fixed_location.column(), 5);
208 /// // running the same untracked function in a different location gives us the same result
209 /// let second_fixed_location = get_just_one_location();
210 /// assert_eq!(fixed_location.file(), second_fixed_location.file());
211 /// assert_eq!(fixed_location.line(), second_fixed_location.line());
212 /// assert_eq!(fixed_location.column(), second_fixed_location.column());
214 /// let this_location = get_caller_location();
215 /// assert_eq!(this_location.file(), file!());
216 /// assert_eq!(this_location.line(), 29);
217 /// assert_eq!(this_location.column(), 21);
219 /// // running the tracked function in a different location produces a different value
220 /// let another_location = get_caller_location();
221 /// assert_eq!(this_location.file(), another_location.file());
222 /// assert_ne!(this_location.line(), another_location.line());
223 /// assert_ne!(this_location.column(), another_location.column());
226 feature = "track_caller",
227 reason = "uses #[track_caller] which is not yet stable",
231 pub const fn caller() -> &'static Location<'static> {
232 crate::intrinsics::caller_location()
236 impl<'a> Location<'a> {
238 feature = "panic_internals",
239 reason = "internal details of the implementation of the `panic!` \
244 pub const fn internal_constructor(file: &'a str, line: u32, col: u32) -> Self {
245 Location { file, line, col }
248 /// Returns the name of the source file from which the panic originated.
255 /// panic::set_hook(Box::new(|panic_info| {
256 /// if let Some(location) = panic_info.location() {
257 /// println!("panic occurred in file '{}'", location.file());
259 /// println!("panic occurred but can't get location information...");
263 /// panic!("Normal panic");
265 #[stable(feature = "panic_hooks", since = "1.10.0")]
266 pub fn file(&self) -> &str {
270 /// Returns the line number from which the panic originated.
277 /// panic::set_hook(Box::new(|panic_info| {
278 /// if let Some(location) = panic_info.location() {
279 /// println!("panic occurred at line {}", location.line());
281 /// println!("panic occurred but can't get location information...");
285 /// panic!("Normal panic");
287 #[stable(feature = "panic_hooks", since = "1.10.0")]
288 pub fn line(&self) -> u32 {
292 /// Returns the column from which the panic originated.
299 /// panic::set_hook(Box::new(|panic_info| {
300 /// if let Some(location) = panic_info.location() {
301 /// println!("panic occurred at column {}", location.column());
303 /// println!("panic occurred but can't get location information...");
307 /// panic!("Normal panic");
309 #[stable(feature = "panic_col", since = "1.25.0")]
310 pub fn column(&self) -> u32 {
315 #[stable(feature = "panic_hook_display", since = "1.26.0")]
316 impl fmt::Display for Location<'_> {
317 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
318 write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
322 /// An internal trait used by libstd to pass data from libstd to `panic_unwind`
323 /// and other panic runtimes. Not intended to be stabilized any time soon, do
325 #[unstable(feature = "std_internals", issue = "none")]
327 pub unsafe trait BoxMeUp {
328 /// Take full ownership of the contents.
329 /// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in libcore.
331 /// After this method got called, only some dummy default value is left in `self`.
332 /// Calling this method twice, or calling `get` after calling this method, is an error.
334 /// The argument is borrowed because the panic runtime (`__rust_start_panic`) only
335 /// gets a borrowed `dyn BoxMeUp`.
336 fn take_box(&mut self) -> *mut (dyn Any + Send);
338 /// Just borrow the contents.
339 fn get(&mut self) -> &(dyn Any + Send);