diff --git a/src/panic.md b/src/panic.md index 2be7e42fb..49b7c7751 100644 --- a/src/panic.md +++ b/src/panic.md @@ -20,50 +20,59 @@ r[panic.panic_handler] ## The `panic_handler` attribute r[panic.panic_handler.intro] -The *`panic_handler` attribute* can be applied to a function to define the behavior of panics. +The *`panic_handler` [attribute][attributes]* can be applied to a function to define the behavior of panics. -r[panic.panic_handler.allowed-positions] -The `panic_handler` attribute can only be applied to a function with signature `fn(&PanicInfo) -> !`. +> [!EXAMPLE] +> Below is shown a `panic_handler` function that logs the panic message and then halts the thread. +> +> ```rust,ignore +> #![no_std] +> +> use core::fmt::{self, Write}; +> use core::panic::PanicInfo; +> +> struct Sink { +> // .. +> # _0: (), +> } +> # +> # impl Sink { +> # fn new() -> Sink { Sink { _0: () }} +> # } +> # +> # impl fmt::Write for Sink { +> # fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) } +> # } +> +> #[panic_handler] +> fn panic(info: &PanicInfo) -> ! { +> let mut sink = Sink::new(); +> +> // logs "panicked at '$reason', src/main.rs:27:4" to some `sink` +> let _ = writeln!(sink, "{}", info); +> +> loop {} +> } +> ``` > [!NOTE] > The [`PanicInfo`] struct contains information about the location of the panic. +r[panic.panic_handler.syntax] +The `panic_handler` attribute uses the [MetaWord] syntax and thus does not take any inputs. + +r[panic.panic_handler.allowed-positions] +The `panic_handler` attribute may only be applied to a function with signature `fn(&PanicInfo) -> !`. + +r[panic.panic_handler.duplicates] +Duplicate instances of the `panic_handler` attribute on a function are ignored. + +> [!NOTE] +> `rustc` currently warns about unused duplicate `panic_handler` attributes. + r[panic.panic_handler.unique] There must be a single `panic_handler` function in the dependency graph. -Below is shown a `panic_handler` function that logs the panic message and then halts the thread. - - -```rust,ignore -#![no_std] - -use core::fmt::{self, Write}; -use core::panic::PanicInfo; - -struct Sink { - // .. -# _0: (), -} -# -# impl Sink { -# fn new() -> Sink { Sink { _0: () }} -# } -# -# impl fmt::Write for Sink { -# fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) } -# } - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - let mut sink = Sink::new(); - - // logs "panicked at '$reason', src/main.rs:27:4" to some `sink` - let _ = writeln!(sink, "{}", info); - - loop {} -} -``` - r[panic.panic_handler.std] ### Standard behavior