|
| 1 | +# The Rust runtime |
| 2 | + |
| 3 | +This section documents features that define some aspects of the Rust runtime. |
| 4 | + |
| 5 | +## The `panic_handler` attribute |
| 6 | + |
| 7 | +The *`panic_handler` attribute* can only be applied to a function with signature |
| 8 | +`fn(&PanicInfo) -> !`. The function marked with this [attribute] defines the behavior of panics. The |
| 9 | +[`PanicInfo`] struct contains information about the location of the panic. There must be a single |
| 10 | +`panic_handler` function in the dependency graph of a binary, dylib or cdylib crate. |
| 11 | + |
| 12 | +Below is shown a `panic_handler` function that logs the panic message and then halts the |
| 13 | +thread. |
| 14 | + |
| 15 | +<!-- NOTE(ignore) `mdbook test` doesn't support `no_std` code --> |
| 16 | + |
| 17 | +``` rust, ignore |
| 18 | +#![no_std] |
| 19 | +
|
| 20 | +use core::fmt::{self, Write}; |
| 21 | +use core::panic::PanicInfo; |
| 22 | +
|
| 23 | +struct Sink { |
| 24 | + // .. |
| 25 | +# _0: (), |
| 26 | +} |
| 27 | +# |
| 28 | +# impl Sink { |
| 29 | +# fn new() -> Sink { Sink { _0: () }} |
| 30 | +# } |
| 31 | +# |
| 32 | +# impl fmt::Write for Sink { |
| 33 | +# fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) } |
| 34 | +# } |
| 35 | +
|
| 36 | +#[panic_handler] |
| 37 | +fn panic(info: &PanicInfo) -> ! { |
| 38 | + let mut sink = Sink::new(); |
| 39 | +
|
| 40 | + // logs "panicked at '$reason', src/main.rs:27:4" to some `sink` |
| 41 | + let _ = writeln!(sink, "{}", info); |
| 42 | +
|
| 43 | + loop {} |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +### Standard behavior |
| 48 | + |
| 49 | +The standard library provides an implementation of `panic_handler` that |
| 50 | +defaults to unwinding the stack but that can be [changed to abort the |
| 51 | +process][abort]. The standard library's panic behavior can be modified at |
| 52 | +runtime with the [set_hook] function. |
| 53 | + |
| 54 | +[`PanicInfo`]: ../core/panic/struct.PanicInfo.html |
| 55 | +[abort]: ../book/ch09-01-unrecoverable-errors-with-panic.html |
| 56 | +[attribute]: attributes.html |
| 57 | +[set_hook]: ../std/panic/fn.set_hook.html |
0 commit comments