]> git.lizzy.rs Git - rust.git/blob - src/libcore/macros/panic.md
Auto merge of #68363 - Dylan-DPC:rollup-33enndv, r=Dylan-DPC
[rust.git] / src / libcore / 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 [`Option`]
9 and [`Result`][runwrap] enums. Both implementations call `panic!` when they are set
10 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. Each thread's panic can be reaped as the `Box<Any>` type,
14 and the single-argument form of the `panic!` macro will be the value which
15 is transmitted.
16
17 [`Result`] enum is often a better solution for recovering from errors than
18 using the `panic!` macro. This macro should be used to avoid proceeding using
19 incorrect values, such as from external sources. Detailed information about
20 error handling is found in the [book].
21
22 The multi-argument form of this macro panics with a string and has the
23 [`format!`] syntax for building a string.
24
25 See also the macro [`compile_error!`], for raising errors during compilation.
26
27 [runwrap]: ../std/result/enum.Result.html#method.unwrap
28 [`Option`]: ../std/option/enum.Option.html#method.unwrap
29 [`Result`]: ../std/result/enum.Result.html
30 [`format!`]: ../std/macro.format.html
31 [`compile_error!`]: ../std/macro.compile_error.html
32 [book]: ../book/ch09-00-error-handling.html
33
34 # Current implementation
35
36 If the main thread panics it will terminate all your threads and end your
37 program with code `101`.
38
39 # Examples
40
41 ```should_panic
42 # #![allow(unreachable_code)]
43 panic!();
44 panic!("this is a terrible mistake!");
45 panic!(4); // panic with the value of 4 to be collected elsewhere
46 panic!("this is a {} {message}", "fancy", message = "message");
47 ```