Skip to content

Commit ccb704c

Browse files
committed
Update panic docs to make it clearer when to use panic vs Result
1 parent 297a801 commit ccb704c

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

library/core/src/macros/panic.md

+19-7
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
Panics the current thread.
22

33
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.
4+
to the caller of the program.
65

76
This macro is the perfect way to assert conditions in example code and in
87
tests. `panic!` is closely tied with the `unwrap` method of both
@@ -21,13 +20,25 @@ Inside the hook a panic can be accessed as a `&dyn Any + Send`,
2120
which contains either a `&str` or `String` for regular `panic!()` invocations.
2221
To panic with a value of another other type, [`panic_any`] can be used.
2322

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-
2923
See also the macro [`compile_error!`], for raising errors during compilation.
3024

25+
# When to use `panic!` vs `Result`
26+
27+
The Rust model of error handling groups errors into two major categories:
28+
recoverable and unrecoverable errors. For a recoverable error, such as a file
29+
not found error, it’s reasonable to report the problem to the user and retry
30+
the operation. Unrecoverable errors are always symptoms of bugs, like trying to
31+
access a location beyond the end of an array.
32+
33+
The Rust language and standard library provides `Result` and `panic!` as parts
34+
of two complementary systems for representing, reporting, propagating, reacting
35+
to, and discarding errors for in these two categories.
36+
37+
The `panic!` macro is provided to represent unrecoverable errors, whereas the
38+
`Result` enum is provided to represent recoverable errors. For more detailed
39+
information about error handling check out the [book] or the [`std::result`]
40+
module docs.
41+
3142
[ounwrap]: Option::unwrap
3243
[runwrap]: Result::unwrap
3344
[`std::panic::set_hook()`]: ../std/panic/fn.set_hook.html
@@ -36,6 +47,7 @@ See also the macro [`compile_error!`], for raising errors during compilation.
3647
[`Any`]: crate::any::Any
3748
[`format!`]: ../std/macro.format.html
3849
[book]: ../book/ch09-00-error-handling.html
50+
[`std::result`]: ../std/result/index.html
3951

4052
# Current implementation
4153

0 commit comments

Comments
 (0)