1 //! Panic support in the standard library.
3 #![unstable(feature = "core_panic_info",
4 reason = "newly available in libcore",
10 /// A struct providing information about a panic.
12 /// `PanicInfo` structure is passed to a panic hook set by the [`set_hook`]
15 /// [`set_hook`]: ../../std/panic/fn.set_hook.html
22 /// panic::set_hook(Box::new(|panic_info| {
23 /// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
24 /// println!("panic occurred: {:?}", s);
26 /// println!("panic occurred");
30 /// panic!("Normal panic");
32 #[lang = "panic_info"]
33 #[stable(feature = "panic_hooks", since = "1.10.0")]
35 pub struct PanicInfo<'a> {
36 payload: &'a (dyn Any + Send),
37 message: Option<&'a fmt::Arguments<'a>>,
38 location: &'a Location<'a>,
41 impl<'a> PanicInfo<'a> {
42 #![unstable(feature = "panic_internals",
43 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>,
62 pub fn set_payload(&mut self, info: &'a (dyn Any + Send)) {
66 /// Returns the payload associated with the panic.
68 /// This will commonly, but not always, be a `&'static str` or [`String`].
70 /// [`String`]: ../../std/string/struct.String.html
77 /// panic::set_hook(Box::new(|panic_info| {
78 /// println!("panic occurred: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
81 /// panic!("Normal panic");
83 #[stable(feature = "panic_hooks", since = "1.10.0")]
84 pub fn payload(&self) -> &(dyn Any + Send) {
88 /// If the `panic!` macro from the `core` crate (not from `std`)
89 /// was used with a formatting string and some additional arguments,
90 /// returns that message ready to be used for example with [`fmt::write`]
92 /// [`fmt::write`]: ../fmt/fn.write.html
93 #[unstable(feature = "panic_info_message", issue = "44489")]
94 pub fn message(&self) -> Option<&fmt::Arguments<'_>> {
98 /// Returns information about the location from which the panic originated,
101 /// This method will currently always return [`Some`], but this may change
102 /// in future versions.
104 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
111 /// panic::set_hook(Box::new(|panic_info| {
112 /// if let Some(location) = panic_info.location() {
113 /// println!("panic occurred in file '{}' at line {}", location.file(),
114 /// location.line());
116 /// println!("panic occurred but can't get location information...");
120 /// panic!("Normal panic");
122 #[stable(feature = "panic_hooks", since = "1.10.0")]
123 pub fn location(&self) -> Option<&Location<'_>> {
124 // NOTE: If this is changed to sometimes return None,
125 // deal with that case in std::panicking::default_hook and std::panicking::begin_panic_fmt.
130 #[stable(feature = "panic_hook_display", since = "1.26.0")]
131 impl fmt::Display for PanicInfo<'_> {
132 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
133 formatter.write_str("panicked at ")?;
134 if let Some(message) = self.message {
135 write!(formatter, "'{}', ", message)?
136 } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
137 write!(formatter, "'{}', ", payload)?
139 // NOTE: we cannot use downcast_ref::<String>() here
140 // since String is not available in libcore!
141 // The payload is a String when `std::panic!` is called with multiple arguments,
142 // but in that case the message is also available.
144 self.location.fmt(formatter)
148 /// A struct containing information about the location of a panic.
150 /// This structure is created by the [`location`] method of [`PanicInfo`].
152 /// [`location`]: ../../std/panic/struct.PanicInfo.html#method.location
153 /// [`PanicInfo`]: ../../std/panic/struct.PanicInfo.html
160 /// panic::set_hook(Box::new(|panic_info| {
161 /// if let Some(location) = panic_info.location() {
162 /// println!("panic occurred in file '{}' at line {}", location.file(), location.line());
164 /// println!("panic occurred but can't get location information...");
168 /// panic!("Normal panic");
170 #[lang = "panic_location"]
172 #[stable(feature = "panic_hooks", since = "1.10.0")]
173 pub struct Location<'a> {
179 impl<'a> Location<'a> {
180 /// Returns the source location of the caller of this function. If that function's caller is
181 /// annotated then its call location will be returned, and so on up the stack to the first call
182 /// within a non-tracked function body.
187 /// #![feature(track_caller)]
188 /// use core::panic::Location;
190 /// /// Returns the [`Location`] at which it is called.
192 /// fn get_caller_location() -> &'static Location<'static> {
193 /// Location::caller()
196 /// /// Returns a [`Location`] from within this function's definition.
197 /// fn get_just_one_location() -> &'static Location<'static> {
198 /// get_caller_location()
201 /// let fixed_location = get_just_one_location();
202 /// assert_eq!(fixed_location.file(), file!());
203 /// assert_eq!(fixed_location.line(), 15);
204 /// assert_eq!(fixed_location.column(), 5);
206 /// // running the same untracked function in a different location gives us the same result
207 /// let second_fixed_location = get_just_one_location();
208 /// assert_eq!(fixed_location.file(), second_fixed_location.file());
209 /// assert_eq!(fixed_location.line(), second_fixed_location.line());
210 /// assert_eq!(fixed_location.column(), second_fixed_location.column());
212 /// let this_location = get_caller_location();
213 /// assert_eq!(this_location.file(), file!());
214 /// assert_eq!(this_location.line(), 29);
215 /// assert_eq!(this_location.column(), 21);
217 /// // running the tracked function in a different location produces a different value
218 /// let another_location = get_caller_location();
219 /// assert_eq!(this_location.file(), another_location.file());
220 /// assert_ne!(this_location.line(), another_location.line());
221 /// assert_ne!(this_location.column(), another_location.column());
223 #[cfg(not(bootstrap))]
224 #[unstable(feature = "track_caller",
225 reason = "uses #[track_caller] which is not yet stable",
228 pub const fn caller() -> &'static Location<'static> {
229 crate::intrinsics::caller_location()
233 impl<'a> Location<'a> {
234 #![unstable(feature = "panic_internals",
235 reason = "internal details of the implementation of the `panic!` \
239 pub const fn internal_constructor(file: &'a str, line: u32, col: u32) -> Self {
240 Location { file, line, col }
243 /// Returns the name of the source file from which the panic originated.
250 /// panic::set_hook(Box::new(|panic_info| {
251 /// if let Some(location) = panic_info.location() {
252 /// println!("panic occurred in file '{}'", location.file());
254 /// println!("panic occurred but can't get location information...");
258 /// panic!("Normal panic");
260 #[stable(feature = "panic_hooks", since = "1.10.0")]
261 pub fn file(&self) -> &str {
265 /// Returns the line number from which the panic originated.
272 /// panic::set_hook(Box::new(|panic_info| {
273 /// if let Some(location) = panic_info.location() {
274 /// println!("panic occurred at line {}", location.line());
276 /// println!("panic occurred but can't get location information...");
280 /// panic!("Normal panic");
282 #[stable(feature = "panic_hooks", since = "1.10.0")]
283 pub fn line(&self) -> u32 {
287 /// Returns the column from which the panic originated.
294 /// panic::set_hook(Box::new(|panic_info| {
295 /// if let Some(location) = panic_info.location() {
296 /// println!("panic occurred at column {}", location.column());
298 /// println!("panic occurred but can't get location information...");
302 /// panic!("Normal panic");
304 #[stable(feature = "panic_col", since = "1.25.0")]
305 pub fn column(&self) -> u32 {
310 #[stable(feature = "panic_hook_display", since = "1.26.0")]
311 impl fmt::Display for Location<'_> {
312 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313 write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
317 /// An internal trait used by libstd to pass data from libstd to `panic_unwind`
318 /// and other panic runtimes. Not intended to be stabilized any time soon, do
320 #[unstable(feature = "std_internals", issue = "0")]
322 pub unsafe trait BoxMeUp {
323 /// Take full ownership of the contents.
324 /// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in libcore.
326 /// After this method got called, only some dummy default value is left in `self`.
327 /// Calling this method twice, or calling `get` after calling this method, is an error.
329 /// The argument is borrowed because the panic runtime (`__rust_start_panic`) only
330 /// gets a borrowed `dyn BoxMeUp`.
331 fn take_box(&mut self) -> *mut (dyn Any + Send);
333 /// Just borrow the contents.
334 fn get(&mut self) -> &(dyn Any + Send);