]> git.proxmox.com Git - rustc.git/blob - library/core/src/macros/panic.md
New upstream version 1.51.0+dfsg1
[rustc.git] / library / core / src / macros / panic.md
1 Panics the current thread.
2
3 This allows a program to terminate immediately and provide feedback
4 to the caller of the program. `panic!` should be used when a program reaches
5 an unrecoverable state.
6
7 This macro is the perfect way to assert conditions in example code and in
8 tests. `panic!` is closely tied with the `unwrap` method of both
9 [`Option`][ounwrap] and [`Result`][runwrap] enums. Both implementations call
10 `panic!` when they are set to [`None`] or [`Err`] variants.
11
12 This macro is used to inject panic into a Rust thread, causing the thread to
13 panic entirely. This macro panics with a string and uses the [`format!`] syntax
14 for building the message.
15
16 Each thread's panic can be reaped as the [`Box`]`<`[`Any`]`>` type,
17 which contains either a `&str` or `String` for regular `panic!()` invocations.
18 To panic with a value of another other type, [`panic_any`] can be used.
19
20 [`Result`] enum is often a better solution for recovering from errors than
21 using the `panic!` macro. This macro should be used to avoid proceeding using
22 incorrect values, such as from external sources. Detailed information about
23 error handling is found in the [book].
24
25 See also the macro [`compile_error!`], for raising errors during compilation.
26
27 [ounwrap]: Option::unwrap
28 [runwrap]: Result::unwrap
29 [`panic_any`]: ../std/panic/fn.panic_any.html
30 [`Box`]: ../std/boxed/struct.Box.html
31 [`Any`]: crate::any::Any
32 [`format!`]: ../std/macro.format.html
33 [book]: ../book/ch09-00-error-handling.html
34
35 # Current implementation
36
37 If the main thread panics it will terminate all your threads and end your
38 program with code `101`.
39
40 # Examples
41
42 ```should_panic
43 # #![allow(unreachable_code)]
44 panic!();
45 panic!("this is a terrible mistake!");
46 panic!("this is a {} {message}", "fancy", message = "message");
47 std::panic::panic_any(4); // panic with the value of 4 to be collected elsewhere
48 ```