]> git.lizzy.rs Git - rust.git/blob - library/core/src/macros/panic.md
Merge commit '39683d8eb7a32a74bea96ecbf1e87675d3338506' into sync_cg_gcc-2022-03-26
[rust.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 When using `panic!()` you can specify a string payload, that is built using
13 the [`format!`] syntax. That payload is used when injecting the panic into
14 the calling Rust thread, causing the thread to panic entirely.
15
16 The behavior of the default `std` hook, i.e. the code that runs directly
17 after the panic is invoked, is to print the message payload to
18 `stderr` along with the file/line/column information of the `panic!()`
19 call. You can override the panic hook using [`std::panic::set_hook()`].
20 Inside the hook a panic can be accessed as a `&dyn Any + Send`,
21 which contains either a `&str` or `String` for regular `panic!()` invocations.
22 To panic with a value of another other type, [`panic_any`] can be used.
23
24 [`Result`] enum is often a better solution for recovering from errors than
25 using the `panic!` macro. This macro should be used to avoid proceeding using
26 incorrect values, such as from external sources. Detailed information about
27 error handling is found in the [book].
28
29 See also the macro [`compile_error!`], for raising errors during compilation.
30
31 [ounwrap]: Option::unwrap
32 [runwrap]: Result::unwrap
33 [`std::panic::set_hook()`]: ../std/panic/fn.set_hook.html
34 [`panic_any`]: ../std/panic/fn.panic_any.html
35 [`Box`]: ../std/boxed/struct.Box.html
36 [`Any`]: crate::any::Any
37 [`format!`]: ../std/macro.format.html
38 [book]: ../book/ch09-00-error-handling.html
39
40 # Current implementation
41
42 If the main thread panics it will terminate all your threads and end your
43 program with code `101`.
44
45 # Examples
46
47 ```should_panic
48 # #![allow(unreachable_code)]
49 panic!();
50 panic!("this is a terrible mistake!");
51 panic!("this is a {} {message}", "fancy", message = "message");
52 std::panic::panic_any(4); // panic with the value of 4 to be collected elsewhere
53 ```