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!` and related macros",
47 pub fn internal_constructor(
48 message: Option<&'a fmt::Arguments<'a>>,
49 location: &'a Location<'a>,
52 PanicInfo { location, message, payload: &NoPayload }
56 feature = "panic_internals",
57 reason = "internal details of the implementation of the `panic!` and related macros",
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 /// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
79 /// println!("panic occurred: {:?}", s);
81 /// println!("panic occurred");
85 /// panic!("Normal panic");
87 #[stable(feature = "panic_hooks", since = "1.10.0")]
88 pub fn payload(&self) -> &(dyn Any + Send) {
92 /// If the `panic!` macro from the `core` crate (not from `std`)
93 /// was used with a formatting string and some additional arguments,
94 /// returns that message ready to be used for example with [`fmt::write`]
96 /// [`fmt::write`]: ../fmt/fn.write.html
97 #[unstable(feature = "panic_info_message", issue = "66745")]
98 pub fn message(&self) -> Option<&fmt::Arguments<'_>> {
102 /// Returns information about the location from which the panic originated,
105 /// This method will currently always return [`Some`], but this may change
106 /// in future versions.
108 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
115 /// panic::set_hook(Box::new(|panic_info| {
116 /// if let Some(location) = panic_info.location() {
117 /// println!("panic occurred in file '{}' at line {}",
122 /// println!("panic occurred but can't get location information...");
126 /// panic!("Normal panic");
128 #[stable(feature = "panic_hooks", since = "1.10.0")]
129 pub fn location(&self) -> Option<&Location<'_>> {
130 // NOTE: If this is changed to sometimes return None,
131 // deal with that case in std::panicking::default_hook and std::panicking::begin_panic_fmt.
136 #[stable(feature = "panic_hook_display", since = "1.26.0")]
137 impl fmt::Display for PanicInfo<'_> {
138 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
139 formatter.write_str("panicked at ")?;
140 if let Some(message) = self.message {
141 write!(formatter, "'{}', ", message)?
142 } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
143 write!(formatter, "'{}', ", payload)?
145 // NOTE: we cannot use downcast_ref::<String>() here
146 // since String is not available in libcore!
147 // The payload is a String when `std::panic!` is called with multiple arguments,
148 // but in that case the message is also available.
150 self.location.fmt(formatter)
154 /// A struct containing information about the location of a panic.
156 /// This structure is created by the [`location`] method of [`PanicInfo`].
158 /// [`location`]: ../../std/panic/struct.PanicInfo.html#method.location
159 /// [`PanicInfo`]: ../../std/panic/struct.PanicInfo.html
166 /// panic::set_hook(Box::new(|panic_info| {
167 /// if let Some(location) = panic_info.location() {
168 /// println!("panic occurred in file '{}' at line {}", location.file(), location.line());
170 /// println!("panic occurred but can't get location information...");
174 /// panic!("Normal panic");
176 #[lang = "panic_location"]
178 #[stable(feature = "panic_hooks", since = "1.10.0")]
179 pub struct Location<'a> {
185 impl<'a> Location<'a> {
186 /// Returns the source location of the caller of this function. If that function's caller is
187 /// annotated then its call location will be returned, and so on up the stack to the first call
188 /// within a non-tracked function body.
193 /// use core::panic::Location;
195 /// /// Returns the [`Location`] at which it is called.
197 /// fn get_caller_location() -> &'static Location<'static> {
198 /// Location::caller()
201 /// /// Returns a [`Location`] from within this function's definition.
202 /// fn get_just_one_location() -> &'static Location<'static> {
203 /// get_caller_location()
206 /// let fixed_location = get_just_one_location();
207 /// assert_eq!(fixed_location.file(), file!());
208 /// assert_eq!(fixed_location.line(), 14);
209 /// assert_eq!(fixed_location.column(), 5);
211 /// // running the same untracked function in a different location gives us the same result
212 /// let second_fixed_location = get_just_one_location();
213 /// assert_eq!(fixed_location.file(), second_fixed_location.file());
214 /// assert_eq!(fixed_location.line(), second_fixed_location.line());
215 /// assert_eq!(fixed_location.column(), second_fixed_location.column());
217 /// let this_location = get_caller_location();
218 /// assert_eq!(this_location.file(), file!());
219 /// assert_eq!(this_location.line(), 28);
220 /// assert_eq!(this_location.column(), 21);
222 /// // running the tracked function in a different location produces a different value
223 /// let another_location = get_caller_location();
224 /// assert_eq!(this_location.file(), another_location.file());
225 /// assert_ne!(this_location.line(), another_location.line());
226 /// assert_ne!(this_location.column(), another_location.column());
228 #[stable(feature = "track_caller", since = "1.46.0")]
229 #[rustc_const_unstable(feature = "const_caller_location", issue = "47809")]
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!` and related macros",
243 pub const fn internal_constructor(file: &'a str, line: u32, col: u32) -> Self {
244 Location { file, line, col }
247 /// Returns the name of the source file from which the panic originated.
254 /// panic::set_hook(Box::new(|panic_info| {
255 /// if let Some(location) = panic_info.location() {
256 /// println!("panic occurred in file '{}'", location.file());
258 /// println!("panic occurred but can't get location information...");
262 /// panic!("Normal panic");
264 #[stable(feature = "panic_hooks", since = "1.10.0")]
265 pub fn file(&self) -> &str {
269 /// Returns the line number from which the panic originated.
276 /// panic::set_hook(Box::new(|panic_info| {
277 /// if let Some(location) = panic_info.location() {
278 /// println!("panic occurred at line {}", location.line());
280 /// println!("panic occurred but can't get location information...");
284 /// panic!("Normal panic");
286 #[stable(feature = "panic_hooks", since = "1.10.0")]
287 pub fn line(&self) -> u32 {
291 /// Returns the column from which the panic originated.
298 /// panic::set_hook(Box::new(|panic_info| {
299 /// if let Some(location) = panic_info.location() {
300 /// println!("panic occurred at column {}", location.column());
302 /// println!("panic occurred but can't get location information...");
306 /// panic!("Normal panic");
308 #[stable(feature = "panic_col", since = "1.25.0")]
309 pub fn column(&self) -> u32 {
314 #[stable(feature = "panic_hook_display", since = "1.26.0")]
315 impl fmt::Display for Location<'_> {
316 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
317 write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
321 /// An internal trait used by libstd to pass data from libstd to `panic_unwind`
322 /// and other panic runtimes. Not intended to be stabilized any time soon, do
324 #[unstable(feature = "std_internals", issue = "none")]
326 pub unsafe trait BoxMeUp {
327 /// Take full ownership of the contents.
328 /// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in libcore.
330 /// After this method got called, only some dummy default value is left in `self`.
331 /// Calling this method twice, or calling `get` after calling this method, is an error.
333 /// The argument is borrowed because the panic runtime (`__rust_start_panic`) only
334 /// gets a borrowed `dyn BoxMeUp`.
335 fn take_box(&mut self) -> *mut (dyn Any + Send);
337 /// Just borrow the contents.
338 fn get(&mut self) -> &(dyn Any + Send);